Skip to content

Commit 036e221

Browse files
committed
design add and search words data structure solution
1 parent ff1251b commit 036e221

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
class TNode {
2+
isEndOf: boolean;
3+
children: Map<string, TNode>;
4+
5+
constructor() {
6+
this.isEndOf = false;
7+
this.children = new Map<string, TNode>();
8+
}
9+
}
10+
11+
class WordDictionary {
12+
private root: TNode;
13+
14+
constructor() {
15+
this.root = new TNode();
16+
}
17+
18+
addWord(word: string): void {
19+
let current = this.root;
20+
21+
for (const ch of word) {
22+
if (!current.children.has(ch)) {
23+
current.children.set(ch, new TNode());
24+
}
25+
26+
current = current.children.get(ch)!;
27+
}
28+
29+
current.isEndOf = true;
30+
}
31+
32+
search(word: string): boolean {
33+
const find = (node: TNode, index: number): boolean => {
34+
if (index === word.length) {
35+
if (node.isEndOf) return true;
36+
return false;
37+
}
38+
39+
const currentCh = word[index];
40+
41+
if (currentCh === ".") {
42+
for (const [ch, child] of node.children) {
43+
if (find(child, index + 1)) return true;
44+
}
45+
46+
return false;
47+
} else {
48+
const child = node.children.get(currentCh);
49+
if (child) {
50+
return find(child, index + 1);
51+
}
52+
53+
return false;
54+
}
55+
56+
return false;
57+
};
58+
59+
return find(this.root, 0);
60+
}
61+
}
62+
63+
/**
64+
* Your WordDictionary object will be instantiated and called as such:
65+
* var obj = new WordDictionary()
66+
* obj.addWord(word)
67+
* var param_2 = obj.search(word)
68+
*/

0 commit comments

Comments
 (0)