Skip to content

Commit 980e610

Browse files
committed
feat(soobing): implement-trie-prefix-tree
1 parent 742008b commit 980e610

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class TrieNode {
2+
children: Map<string, TrieNode>;
3+
isEnd: boolean;
4+
5+
constructor() {
6+
this.children = new Map();
7+
this.isEnd = false;
8+
}
9+
}
10+
11+
class Trie {
12+
root: TrieNode;
13+
14+
constructor() {
15+
this.root = new TrieNode();
16+
}
17+
18+
insert(word: string): void {
19+
let node = this.root;
20+
for (const char of word) {
21+
if (!node.children.has(char)) {
22+
node.children.set(char, new TrieNode());
23+
}
24+
node = node.children.get(char)!;
25+
}
26+
node.isEnd = true;
27+
}
28+
29+
search(word: string): boolean {
30+
const node = this._findNode(word);
31+
return node !== null && node.isEnd;
32+
}
33+
34+
startsWith(prefix: string): boolean {
35+
return this._findNode(prefix) !== null;
36+
}
37+
38+
private _findNode(word: string): TrieNode | null {
39+
let node = this.root;
40+
for (const char of word) {
41+
if (!node.children.has(char)) return null;
42+
node = node.children.get(char)!;
43+
}
44+
return node;
45+
}
46+
}

0 commit comments

Comments
 (0)