Skip to content

Commit 1cf59f6

Browse files
Jeehay28Jeehay28
authored andcommitted
Add design-add-and-search-words-data-structure solution in TypeScript
1 parent eaed2a9 commit 1cf59f6

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
class WordDictionary {
2+
root: {
3+
[key: string]: any;
4+
};
5+
6+
constructor() {
7+
this.root = { $: true }; // ending
8+
}
9+
10+
// {
11+
// "$": true,
12+
// "b": {
13+
// "$": false,
14+
// "a": {
15+
// "$": false,
16+
// "d": {
17+
// "$": true
18+
// }
19+
// }
20+
// }
21+
// }
22+
23+
// TC: O(w)
24+
// SC: O(w)
25+
addWord(word: string): void {
26+
let node = this.root;
27+
28+
for (const ch of word) {
29+
if (!node[ch]) {
30+
node[ch] = { $: false };
31+
}
32+
node = node[ch];
33+
}
34+
35+
node["$"] = true;
36+
}
37+
38+
// TC: O(26^w)
39+
// SC: O(w)
40+
search(word: string): boolean {
41+
const dfs = (node, idx: number) => {
42+
if (idx === word.length) {
43+
return node["$"];
44+
}
45+
46+
const ch = word[idx];
47+
48+
if (node[ch]) {
49+
return dfs(node[ch], idx + 1);
50+
}
51+
52+
if (ch === ".") {
53+
for (const key of Object.keys(node)) {
54+
if (key !== "$" && dfs(node[key], idx + 1)) {
55+
return true;
56+
}
57+
}
58+
}
59+
60+
return false;
61+
};
62+
63+
return dfs(this.root, 0);
64+
}
65+
}
66+
67+
/**
68+
* Your WordDictionary object will be instantiated and called as such:
69+
* var obj = new WordDictionary()
70+
* obj.addWord(word)
71+
* var param_2 = obj.search(word)
72+
*/
73+

0 commit comments

Comments
 (0)