Medium
这题讲真不是很懂
class TrieNode{
HashMap<Character, TrieNode> children = new HashMap<>();
char c;
boolean isWord;
public TrieNode(){
}
public TrieNode(char c){
this.c = c;
}
}
public class WordDictionary {
public TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
this.root = new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode curt = root;
HashMap<Character, TrieNode> curtChildren = curt.children;
for (int i = 0; i < word.length(); i++){
char curtChar = word.charAt(i);
if (curtChildren.containsKey(curtChar)){
curt = curtChildren.get(curtChar);
} else {
TrieNode newNode = new TrieNode(curtChar);
curtChildren.put(curtChar, newNode);
curt = newNode;
}
curtChildren = curt.children;
if (i == word.length() - 1){
curt.isWord = true;
}
}
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return dfsSearch(word, 0, root);
}
public boolean dfsSearch(String s, int index, TrieNode curt){
HashMap<Character, TrieNode> children = curt.children;
if (index == s.length()){
if (children.size() == 0){
return true;
} else {
return false;
}
}
char c = s.charAt(index);
if (children.containsKey(c)){
if (index == s.length() - 1 && children.get(c).isWord){
return true;
}
return dfsSearch(s, index + 1, children.get(c));
} else if (c == '.'){
boolean result = false;
for (Map.Entry<Character, TrieNode> child : children.entrySet()){
if (index == s.length() - 1 && child.getValue().isWord){
return true;
}
if (dfsSearch(s, index + 1, child.getValue())){
result = true;
}
}
return result;
} else {
return false;
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/