Note:
You may assume that all words are consist of lowercase lettersa-z.
2. Implementation
(1) Trie + Backtracking
class WordDictionary {
class TrieNode {
char val;
boolean isWord;
TrieNode[] childNode;
public TrieNode(char val) {
this.val = val;
childNode = new TrieNode[26];
}
}
TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new TrieNode(' ');
}
/** Adds a word into the data structure. */
public void addWord(String word) {
if (word == null || word.length() == 0) {
return;
}
TrieNode curNode = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (curNode.childNode[index] == null) {
curNode.childNode[index] = new TrieNode(c);
}
curNode = curNode.childNode[index];
}
curNode.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) {
if (word == null || word.length() == 0) {
return false;
}
return searchByDFS(root, 0, word);
}
public boolean searchByDFS(TrieNode node, int depth, String word) {
if (depth == word.length()) {
return node.isWord;
}
char c = word.charAt(depth);
if (c == '.') {
for (TrieNode childNode : node.childNode) {
if (childNode != null && searchByDFS(childNode, depth + 1, word)) {
return true;
}
}
return false;
}
else {
int index = c - 'a';
return node.childNode[index] != null && searchByDFS(node.childNode[index], depth + 1, word);
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/