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-z
or.
. A.
means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase lettersa-z
.
class WordDictionary {
class Node {
//public char c;
public Node[] children;
public boolean isLeaf;
public Node() {
this.children = new Node[26];
}
}
private Node root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new Node();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
Node temp = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(temp.children[c - 'a'] == null) {
temp.children[c - 'a'] = new Node();
}
temp = temp.children[c - 'a'];
}
temp.isLeaf = 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 search(root, 0, word);
}
public boolean search(Node root, int start, String word) {
if(start == word.length()) {
return root.isLeaf;
}
char c = word.charAt(start);
if(c == '.') {
for(int i = 0; i < root.children.length; i++) {
if(root.children[i] != null) {
if(search(root.children[i], start + 1, word))
return true;
}
}
return false;
} else {
if(root.children[c - 'a'] == null)
return false;
return search(root.children[c - 'a'], start + 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);
*/