Add and Search Word - Data structure design
Source
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 letters a-z or .. A . means it can represent any one letter.
Example
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") // return false
search("bad") // return true
search(".ad") // return true
search("b..") // return true
Note
You may assume that all words are consist of lowercase letters a-z.
Java
class TrieNode{
TrieNode[] children;
boolean isEndOfWord;
public TrieNode() {
this.isEndOfWord = false;
this.children = new TrieNode[26];
}
}
public class WordDictionary {
private TrieNode root;
public WordDictionary(){
root = new TrieNode();
}
public void addWord(String word) {
TrieNode runner = root;
for(char c : word.toCharArray()){
if(runner.children[c-'a']==null){
runner.children[c-'a'] = new TrieNode();
}
runner = runner.children[c-'a'];
}
runner.isEndOfWord = true;
}
public boolean search(String word) {
return match(word.toCharArray(), 0, root);
}
public boolean match(char[] word, int k, TrieNode node) {
if (k == word.length) return node.isEndOfWord;
if (word[k] != '.') {
return node.children[word[k] - 'a'] != null && match(word, k+1, node.children[word[k] - 'a']);
}
else {
for (int i = 0; i < node.children.length; i++) {
if (node.children[i] != null) {
if (match(word, k+1, node.children[i])) return true;
}
}
}
return false;
}
}