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
Note:
You may assume that all words are consist of lowercase letters a-z
.
You should be familiar with how a Trie works. If not, please work on this problem:
Implement Trie (Prefix Tree) first.
思路:这道题如果做过之前的那道
Implement Trie (Prefix Tree) 实现字典树(前缀树)的话就没有太大的难度了,因为这道题里面'.'可以代替任意字符,所以一旦有了'.',就需要查找之前存下的所有下一层的不是null的path;String match 的题,一般都是DFS 参数里面加入index,然后递归 subproblem求解;
class WordDictionary {
class TrieNode {
public TrieNode[] children;
public boolean isword;
public String word;
public TrieNode() {
this.children = new TrieNode[26];
this.isword = false;
this.word = null;
}
}
class Trie {
public TrieNode root;
public Trie() {
this.root = new TrieNode();
}
public void insert(String word) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(cur.children[c - 'a'] == null) {
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
}
cur.isword = true;
cur.word = word;
}
public boolean search(String word) {
return searchHelper(word, root, 0);
}
private boolean searchHelper(String word, TrieNode cur, int index) {
if(index == word.length()) {
return cur.isword;
}
char c = word.charAt(index);
if(c == '.') {
for(int i = 0; i < 26; i++) {
if(cur.children[i] != null) {
if(searchHelper(word, cur.children[i], index + 1)) {
return true;
}
}
}
return false;
} else {
if(cur.children[c - 'a'] == null) {
return false;
} else {
return searchHelper(word, cur.children[c - 'a'], index + 1);
}
}
}
}
private Trie trie;
public WordDictionary() {
this.trie = new Trie();
}
public void addWord(String word) {
trie.insert(word);
}
public boolean search(String word) {
return trie.search(word);
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/