public class WordDictionary {
TrieNode root = new TrieNode();
public WordDictionary() {
}
public void addWord(String word) {
TrieNode ws = root;
for (char ch : word.toCharArray()) {
if (ws.child[ch - 'a'] == null) {
ws.child[ch - 'a'] = new TrieNode();
}
ws = ws.child[ch - 'a'];
}
ws.isWord = true;
}
public boolean search(String word) {
return find(word, 0, root);
}
public boolean find(String word, int index, TrieNode node) {
if (index == word.length()) {
return node.isWord;
}
Character c = word.charAt(index);
if (c == '.') {
for (int i = 0; i < 26; i++) {
if (node.child[i] != null) {
if (find(word, index + 1, node.child[i]))
return true;
}
}
return false;
} else if (node.child[c - 'a'] != null) {
return find(word, index + 1, node.child[c - 'a']);
}
else {
return false;
}
}
}
class TrieNode {
boolean isWord;
TrieNode[] child = new TrieNode[26];
}