-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathwordDictionary.js
53 lines (45 loc) · 1.32 KB
/
wordDictionary.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
class Node {
constructor() {
this.children = {};
this.isEndOfWord = false;
}
}
class WordDictionary {
constructor() {
this.root = new Node();
}
addWord(word) {
let curr = this.root;
for(let ch of word) {
if(!(ch in curr.children)) {
curr.children[ch] = new Node();
}
curr = curr.children[ch];
}
curr.isEndOfWord = true;
}
searchWord(word) {
return this.dfs(word, 0, this.root);
}
dfs(word, index, node) {
if(!node) return false;
if(index === word.length) return node.isEndOfWord;
if(word[index] === '.') {
for(const ch of Object.keys(node.children)) {
if(this.dfs(word, index+1, node.children[ch])) return true;
}
return false;
} else {
if(!node.children[word[index]]) return false;
return this.dfs(word, index+1, node.children[word[index]]);
}
}
}
let wordDictionary = new WordDictionary();
wordDictionary.addWord("bat");
wordDictionary.addWord("cat");
wordDictionary.addWord("rat");
console.log(wordDictionary.searchWord("mat"));
console.log(wordDictionary.searchWord("bat"));
console.log(wordDictionary.searchWord(".at"));
console.log(wordDictionary.searchWord("c.."));