Skip to content

Commit 8c2b30a

Browse files
authored
add 211-Design-Add-and-Search-Words-Data-Structure
1 parent 1b59ccb commit 8c2b30a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class TrieNode {
2+
constructor() {
3+
this.children = {};
4+
this.endOfWord = false;
5+
}
6+
}
7+
8+
class WordDictionary {
9+
constructor() {
10+
this.root = new TrieNode();
11+
}
12+
13+
addWord(word) {
14+
let cur = this.root;
15+
16+
for (const c of word) {
17+
if (!(c in cur.children)) {
18+
cur.children[c] = new TrieNode();
19+
}
20+
cur = cur.children[c];
21+
}
22+
cur.endOfWord = true;
23+
}
24+
25+
search(word) {
26+
function dfs(j, root) {
27+
let cur = root;
28+
29+
for (let i = j; i < word.length; i++) {
30+
const c = word[i];
31+
32+
if (c === ".") {
33+
for (const key in cur.children) {
34+
if (Object.prototype.hasOwnProperty.call(cur.children, key)) {
35+
const child = cur.children[key];
36+
37+
if (dfs(i + 1, child)) {
38+
return true;
39+
}
40+
}
41+
}
42+
return false;
43+
} else {
44+
if (!(c in cur.children)) {
45+
return false;
46+
}
47+
cur = cur.children[c];
48+
}
49+
}
50+
51+
return cur.endOfWord;
52+
}
53+
return dfs(0, this.root);
54+
}
55+
}

0 commit comments

Comments
 (0)