典型的字典树trie题
链接
字典树结构就不再详述,这里的addword操作就如同常规的字典树增加单词的操作。
这里的查询操作有所不同,出现了'.', 这个符号可以代表任意的26字母,那么在查询的时候就要涉及到了递归,如果是字母的话常规查询即可,但一旦遇到通配符的时候,要遍历26个子树,任意一个树满足统通配符及其后面的字符即代表查询成功。这里涉及到了或运算。
代码如下
public class WordDictionary {
Trie t = new Trie();
/*
* @param word: Adds a word into the data structure.
* @return: nothing
*/
public void addWord(String word) {
// write your code here
Trie p = t;
for(int i = 0; i < word.length(); i++){
int idx = word.charAt(i) - 'a';
if(p.subTries[idx] == null){
p.subTries[idx] = new Trie();
}
p = p.subTries[idx];
}
p.end = true;
}
/*
* @param word: A word could contain the dot character '.' to represent any one letter.
* @return: if the word is in the data structure.
*/
public boolean search(String word) {
// write your code here
return searchW(word, t);
}
private boolean searchW(String word, Trie root){
Trie p = root;
for(int i = 0; i < word.length(); i++){
if(word.charAt(i) == '.'){
boolean res = false;
for(int j = 0; j < 26; j++){
if(p.subTries[j] != null){
res |= searchW(word.substring(i+1), p.subTries[j]);
}
}
return res;
}else{
int idx = word.charAt(i) - 'a';
if(p.subTries[idx] == null){
return false;
}
p = p.subTries[idx];
}
}
return p.end == true;
}
}
class Trie{
Trie[] subTries;
boolean end;
public Trie(){
end = false;
subTries = new Trie[26];
}
}