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.ts
62 lines (55 loc) · 1.62 KB
/
0211-design-add-and-search-words-data-structure.ts
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
61
62
class TrieNode {
children: { [key: string]: TrieNode };
endOfWord: boolean;
constructor() {
this.children = {};
this.endOfWord = false;
}
}
class WordDictionary {
root: TrieNode;
constructor() {
this.root = new TrieNode();
}
addWord(word: string): void {
let cur = this.root;
for (const c of word) {
if (!(c in cur.children)) {
cur.children[c] = new TrieNode();
}
cur = cur.children[c];
}
cur.endOfWord = true;
}
search(word: string): boolean {
function dfs(j: number, root: TrieNode): boolean {
let cur = root;
for (let i = j; i < word.length; i++) {
const c = word[i];
if (c === '.') {
for (const key in cur.children) {
if (
Object.prototype.hasOwnProperty.call(
cur.children,
key
)
) {
const child = cur.children[key];
if (dfs(i + 1, child)) {
return true;
}
}
}
return false;
} else {
if (!(c in cur.children)) {
return false;
}
cur = cur.children[c];
}
}
return cur.endOfWord;
}
return dfs(0, this.root);
}
}