Skip to content

Commit f89c4c6

Browse files
committed
Feat: 208. Implement Trie (Prefix Tree)
1 parent c304937 commit f89c4c6

File tree

1 file changed

+47
-0
lines changed

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+
/**
2+
* https://leetcode.com/problems/implement-trie-prefix-tree
3+
*/
4+
class Trie {
5+
constructor(private root: Record<string, any> = {}) {}
6+
7+
insert(word: string): void {
8+
let node = this.root;
9+
for (const char of word) {
10+
if (!node[char]) {
11+
node[char] = {};
12+
}
13+
node = node[char];
14+
}
15+
node.isEnd = true;
16+
}
17+
18+
search(word: string): boolean {
19+
let node = this.root;
20+
for (const char of word) {
21+
if (!node[char]) {
22+
return false;
23+
}
24+
node = node[char];
25+
}
26+
return !!node.isEnd;
27+
}
28+
29+
startsWith(prefix: string): boolean {
30+
let node = this.root;
31+
for (const char of prefix) {
32+
if (!node[char]) {
33+
return false;
34+
}
35+
node = node[char];
36+
}
37+
return true;
38+
}
39+
}
40+
41+
/**
42+
* Your Trie object will be instantiated and called as such:
43+
* var obj = new Trie()
44+
* obj.insert(word)
45+
* var param_2 = obj.search(word)
46+
* var param_3 = obj.startsWith(prefix)
47+
*/

0 commit comments

Comments
 (0)