Skip to content

Commit 04a6a59

Browse files
committed
Implement Trie (Prefix Tree)
1 parent e09e587 commit 04a6a59

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
type ChildTrie = {
2+
value?: string;
3+
isEnd?: boolean;
4+
childrens: ChildrenMap;
5+
};
6+
type ChildrenMap = {
7+
[key: string]: ChildTrie;
8+
};
9+
10+
class Trie {
11+
childrens: ChildrenMap = {};
12+
constructor() {}
13+
14+
insert(word: string): void {
15+
if (word.length === 0) {
16+
return;
17+
}
18+
let current: ChildTrie = {
19+
childrens: this.childrens,
20+
};
21+
for (let i = 0; i < word.length; i++) {
22+
if (current.childrens[word[i]] === undefined) {
23+
current.childrens[word[i]] = { value: word[i], isEnd: false, childrens: {} };
24+
}
25+
26+
current = current.childrens[word[i]];
27+
}
28+
current.isEnd = true;
29+
}
30+
31+
search(word: string): boolean {
32+
let current: ChildTrie = {
33+
childrens: this.childrens,
34+
};
35+
for (let i = 0; i < word.length; i++) {
36+
if (current.childrens[word[i]] === undefined) {
37+
return false;
38+
}
39+
40+
current = current.childrens[word[i]];
41+
}
42+
return current.isEnd ?? false;
43+
}
44+
45+
startsWith(prefix: string): boolean {
46+
let current = this.childrens;
47+
for (let i = 0; i < prefix.length; i++) {
48+
if (current[prefix[i]] === undefined) {
49+
return false;
50+
}
51+
current = current[prefix[i]].childrens;
52+
}
53+
return true;
54+
}
55+
}

0 commit comments

Comments
 (0)