Implement Magic Dictionary LeetCode solution in JavaScript

1
function TrieNode() {
2
this.children = new Map();
3
this.endOfWord = false;
4
}
5

6
var MagicDictionary = function () {
7
this.root = new TrieNode();
8
};
9

10
MagicDictionary.prototype.buildDict = function (dictionary) {
11
for (let word of dictionary) {
12
let curr = this.root;
13
for (let letter of word) {
14
let map = curr.children;
15
if (!map.has(letter)) map.set(letter, new TrieNode());
16
curr = map.get(letter);
17
}
18
curr.endOfWord = true;
19
}
20
};
21

22
MagicDictionary.prototype.search = function (searchWord) {
23
return dfs(this.root, searchWord, 0, 0);
24
};
25

26
function dfs(root, str, i, count) {
27
if (count > 1) return false;
28
if (i == str.length) return count == 1 && root.endOfWord;
29

30
for (let [char, node] of root.children) {
31
let c = 0;
32
if (char != str[i]) c = 1;
33
if (dfs(node, str, i + 1, count + c)) return true;
34
}
35
return false;
36
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0