forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplement Magic Dictionary.js
44 lines (40 loc) · 1.3 KB
/
Implement Magic Dictionary.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
var MagicDictionary = function() {
this.trie = {};
};
MagicDictionary.prototype.buildDict = function(dictionary) {
for(let word of dictionary) {
let curr = this.trie;
for(let c of word) {
if(!curr[c]) curr[c] = {};
curr = curr[c];
}
curr['end'] = true;
}
};
MagicDictionary.prototype.search = function(searchWord) {
const len = searchWord.length;
const searchHelper = (idx = 0, mismatch = 1, curr = this.trie) => {
for(let i = idx; i < len; i++) {
const c = searchWord[i];
if(!curr[c]) {
if(mismatch == 0) return false;
for(let possibleChar in curr) {
if(searchHelper(i + 1, mismatch - 1, curr[possibleChar])) {
return true;
}
}
return false;
} else {
for(let possibleChar in curr) {
if(c == possibleChar) continue;
if(searchHelper(i + 1, mismatch - 1, curr[possibleChar])) {
return true;
}
}
}
curr = curr[c];
}
return Boolean(curr['end'] && mismatch == 0);
}
return searchHelper();
};