Skip to content

Commit 061b78c

Browse files
committed
feat: implement-trie-prefix-tree solution
1 parent 88796e9 commit 061b78c

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 트라이 알고리즘
3+
* 달레 해설을 보고 참고하여 TypeScript로 작성
4+
*/
5+
class Node {
6+
children: { [key: string]: Node };
7+
ending: boolean;
8+
9+
constructor(ending: boolean = false) {
10+
this.children = {};
11+
this.ending = ending;
12+
}
13+
}
14+
15+
class Trie {
16+
private root: Node;
17+
18+
constructor() {
19+
this.root = new Node(true);
20+
}
21+
22+
insert(word: string): void {
23+
let node = this.root;
24+
for (const ch of word) {
25+
if (!(ch in node.children)) {
26+
node.children[ch] = new Node();
27+
}
28+
node = node.children[ch];
29+
}
30+
node.ending = true;
31+
}
32+
33+
search(word: string): boolean {
34+
let node = this.root;
35+
for (const ch of word) {
36+
if (!(ch in node.children)) {
37+
return false;
38+
}
39+
node = node.children[ch];
40+
}
41+
return node.ending;
42+
}
43+
44+
startsWith(prefix: string): boolean {
45+
let node = this.root;
46+
for (const ch of prefix) {
47+
if (!(ch in node.children)) {
48+
return false;
49+
}
50+
node = node.children[ch];
51+
}
52+
return true;
53+
}
54+
}

0 commit comments

Comments
 (0)