Add and Search
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 lettersa-zor.. 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
class WordDictionary {
private class TrieNode {
TrieNode[] children;
boolean isWord;
String word;
private TrieNode() {
children = new TrieNode[26];
isWord = false;
word = "";
}
}
/** Initialize your data structure here. */
TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
int pos = word.charAt(i) - 'a';
if (node.children[pos] == null) {
node.children[pos] = new TrieNode();
}
node = node.children[pos];
}
node.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 find(word, root, 0);
}
public boolean find (String word, TrieNode root, int index) {
if (index == word.length()) {
return root.isWord;
}
if (word.charAt(index) == '.') {
for (TrieNode child : root.children) {
// if (child != null) {
// return find(word, child, index+1);
// }错误原因不详
if(child!= null && find(word, child, index+1)) {
return true;
}
}
return false;
}else{
int c = word.charAt(index) - 'a';
return (root.children[c] != null && find(word, root.children[c], index + 1));
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/