Description
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
问题描述
设计一个支持如下两个操作的数据结构
void addWord(word)
bool search(word)
search(word)可以搜索一个单词字面量或者只包含a- z和’.’的正则表达式。一个’.’可以表示任意字符
所有单词均为小写
问题分析
使用字典树来做,注意字典树节点存放isWord属性,标明该节点存在对应单词
addWord(word)向字典树中添加单词
search(word),遍历word和字典树,若遇到字符’.’,则回溯字典树当前节点的所有分支
解法(字典树)
class TrieNode {
TrieNode[] children;
boolean isWord;
public TrieNode() {
children = new TrieNode[26];
isWord = false;
}
}
public class WordDictionary {
TrieNode root = null;
public WordDictionary() {
root = new TrieNode();
}
public void addWord(String word) {
TrieNode node = root;
for(char c : word.toCharArray()) {
int j = c - 'a';
if(node.children[j] == null) {
node.children[j] = new TrieNode();
}
node = node.children[j];
}
node.isWord = true;
}
public boolean search(String word) {
return find(word, root, 0);
}
private boolean find(String word, TrieNode node, int index) {
//若到达word末尾,判断字典树当前节点是否有对应字符串
if(index == word.length()) return node.isWord;
if(word.charAt(index) == '.') {
//回溯该节点所有分支
for(TrieNode temp : node.children) {
if(temp != null && find(word, temp, index+1)) return true;
}
return false;
}else{
int j = word.charAt(index) - 'a';
TrieNode temp = node.children[j];
return temp != null && find(word, temp, index+1);
}
}
}