Skip to content

Commit 58b8612

Browse files
committed
feat: implement-trie-prefix-tree
1 parent 7161650 commit 58b8612

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class TrieNode {
2+
children: Map<string, TrieNode>;
3+
isEnd: boolean;
4+
constructor() {
5+
this.children = new Map();
6+
this.isEnd = false
7+
}
8+
}
9+
class Trie {
10+
root: TrieNode;
11+
12+
constructor() {
13+
this.root = new TrieNode();
14+
}
15+
16+
insert(word: string): void {
17+
let node = this.root;
18+
for(const ch of word) {
19+
if(!node.children.has(ch)) {
20+
node.children.set(ch, new TrieNode());
21+
}
22+
node = node.children.get(ch)!
23+
}
24+
node.isEnd = true;
25+
}
26+
27+
search(word: string): boolean {
28+
let node = this.root;
29+
for(const ch of word) {
30+
if(!node.children.has(ch)) return false;
31+
node = node.children.get(ch)!;
32+
}
33+
return node.isEnd;
34+
}
35+
36+
startsWith(prefix: string): boolean {
37+
let node = this.root;
38+
for(const ch of prefix) {
39+
if(!node.children.has(ch)) return false;
40+
node = node.children.get(ch)!;
41+
}
42+
return true;
43+
}
44+
}
45+
46+
/**
47+
* Your Trie object will be instantiated and called as such:
48+
* var obj = new Trie()
49+
* obj.insert(word)
50+
* var param_2 = obj.search(word)
51+
* var param_3 = obj.startsWith(prefix)
52+
*/

0 commit comments

Comments
 (0)