forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0211-design-add-and-search-words-data-structure.js
60 lines (46 loc) · 1.34 KB
/
0211-design-add-and-search-words-data-structure.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Your WordDictionary object will be instantiated and called as such:
* var obj = new WordDictionary()
* obj.addWord(word)
* var param_2 = obj.search(word)
*/
class TrieNode {
constructor() {
this.children = {};
this.isWord = false;
}
}
class WordDictionary {
constructor() {
this.root = new TrieNode();
}
/* Time O(N) | Space O(N) */
addWord(word, node = this.root) {
for (const char of word) {
const child = node.children[char] || new TrieNode();
node.children[char] = child;
node = child;
}
node.isWord = true;
}
/* Time O(N) | Space O(N) */
search(word) {
return this.dfs(word, this.root, 0);
}
dfs(word, node, level) {
if (!node) return false;
const isWord = level === word.length;
if (isWord) return node.isWord;
const isWildCard = word[level] === '.';
if (isWildCard) return this.hasWildCard(word, node, level);
return this.dfs(word, node.children[word[level]], level + 1);
}
hasWildCard(word, node, level) {
for (const char of Object.keys(node.children)) {
const child = node.children[char];
const hasWord = this.dfs(word, child, level + 1);
if (hasWord) return true;
}
return false;
}
}