Add and Search Word
void addWord(word)
boolean search(word)addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> trueAnalysis
Solution
class TrieNode {
public boolean isLeaf;
public TrieNode[] children;
public TrieNode() {
this.children = new TrieNode[26];
}
}
public class WordDictionary {
private TrieNode root;
public WordDictionary() {
this.root = new TrieNode();
}
// Adds a word into the data structure.
public void addWord(String word) {
TrieNode p = this.root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (p.children[index] == null) {
TrieNode temp = new TrieNode();
p.children[index] = temp;
}
p = p.children[index];
}
p.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 match(this.root, word, 0);
}
private boolean match(TrieNode p, String word, int k) {
if (k == word.length()) {
return p.isLeaf;
}
if (word.charAt(k) == '.') {
for (int i = 0; i < p.children.length; i++) {
if (p.children[i] != null) {
if (match(p.children[i], word, k + 1)) {
return true;
}
}
}
} else {
int index = word.charAt(k) - 'a';
return p.children[index] != null && match(p.children[index], word, k + 1);
}
return false;
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");Reference
Last updated