Skip to content

Commit 12924f4

Browse files
committed
design-add-and-search-words-data-structure solved
1 parent 61e78eb commit 12924f4

File tree

1 file changed

+47
-0
lines changed
  • design-add-and-search-words-data-structure

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class TrieNode {
2+
constructor() {
3+
this.children = {};
4+
this.word = 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+
for (let c of word) {
16+
if (!cur.children[c]) {
17+
cur.children[c] = new TrieNode();
18+
}
19+
cur = cur.children[c];
20+
}
21+
cur.word = true;
22+
}
23+
24+
search(word) {
25+
const dfs = (j, root) => {
26+
let cur = root;
27+
for (let i = j; i < word.length; i++) {
28+
const c = word[i];
29+
if (c === '.') {
30+
for (let child of Object.values(cur.children)) {
31+
if (dfs(i + 1, child)) {
32+
return true;
33+
}
34+
}
35+
return false;
36+
} else {
37+
if (!cur.children[c]) {
38+
return false;
39+
}
40+
cur = cur.children[c];
41+
}
42+
}
43+
return cur.word;
44+
};
45+
return dfs(0, this.root);
46+
}
47+
}

0 commit comments

Comments
 (0)