211. Design Add and Search Words Data Structure
Last updated
Last updated
time: O(n), n is word len
space: O(n)
class WordDictionary {
class TrieNode {
Map<Character, TrieNode> sons;
boolean isWord;
String word;
TrieNode() {
this.sons = new HashMap<>();
this.isWord = false;
this.word = null;
}
}
private TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
public void addWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
node.sons.computeIfAbsent(c, v -> new TrieNode());
node = node.sons.get(c);
}
node.isWord = true;
node.word = word;
}
public boolean search(String word) {
return find(word, root, 0);
}
private boolean find(String word, TrieNode node, int index) {
if (index == word.length()) {
return node.isWord;
}
if (word.charAt(index) == '.') {
for (TrieNode temp : node.sons.values()) {
if (temp != null && find(word, temp, index+1)) { // if '.', use all sons to do DFS on word's index+1
return true;
}
}
} else {
// only check node's sons has this letter, if has, find on index+1
TrieNode temp = node.sons.get(word.charAt(index));
return temp != null && find(word, temp, index+1);
}
return false;
}
}
/**
跟 208 不同的是, 利用 dfs, 移動 index 來找是否有這個 word
208 search 是用 iteration 的方式, 一個 char 一個 char, node = next 往下找
這裡是透過 dfs 一個一個往下找 char
*/