Skip to content

Commit 1c9a838

Browse files
committed
feat(soobing): week5 > implement-trie-prefix-tree
1 parent 5c535db commit 1c9a838

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* ๋ฌธ์ œ ์œ ํ˜•
3+
* - Trie ๊ตฌํ˜„ (๋ฌธ์ž์—ด ๊ฒ€์ƒ‰)
4+
*
5+
* ๋ฌธ์ œ ์„ค๋ช…
6+
* - ๋ฌธ์ž์—ด ๊ฒ€์ƒ‰/์ถ”์ฒœ/์ž๋™์™„์„ฑ์—์„œ ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š” ์ž๋ฃŒ๊ตฌ์กฐ Trie ๊ตฌํ˜„
7+
*
8+
* ์•„์ด๋””์–ด
9+
* 1) ๋ฌธ์ž์—ด์˜ ๊ฐ ๋ฌธ์ž๋ฅผ TrieNode ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค๋กœ ํ‘œํ˜„s
10+
*
11+
*/
12+
class TrieNode {
13+
children: Map<string, TrieNode>;
14+
isEnd: boolean;
15+
16+
constructor() {
17+
this.children = new Map();
18+
this.isEnd = false;
19+
}
20+
}
21+
22+
class Trie {
23+
root: TrieNode;
24+
constructor() {
25+
this.root = new TrieNode();
26+
}
27+
28+
insert(word: string): void {
29+
let node = this.root;
30+
for (const char of word) {
31+
if (!node.children.has(char)) {
32+
node.children.set(char, new TrieNode());
33+
}
34+
node = node.children.get(char)!;
35+
}
36+
node.isEnd = true;
37+
}
38+
39+
// isEnd ๊นŒ์ง€ ํ™•์ธ์ด ํ•„์š”
40+
search(word: string): boolean {
41+
const node = this._findNode(word);
42+
return node !== null && node.isEnd;
43+
}
44+
45+
// isEnd๊นŒ์ง€ ํ™•์ธ ํ•„์š” ์—†๊ณ  ์กด์žฌ ์—ฌ๋ถ€๋งŒ ํ™•์ธ ํ•„์š”
46+
startsWith(prefix: string): boolean {
47+
return this._findNode(prefix) !== null;
48+
}
49+
50+
private _findNode(word: string): TrieNode | null {
51+
let node = this.root;
52+
for (const char of word) {
53+
if (!node.children.get(char)) return null;
54+
node = node.children.get(char)!;
55+
}
56+
57+
return node;
58+
}
59+
}
60+
61+
/**
62+
* Your Trie object will be instantiated and called as such:
63+
* var obj = new Trie()
64+
* obj.insert(word)
65+
* var param_2 = obj.search(word)
66+
* var param_3 = obj.startsWith(prefix)
67+
*/

0 commit comments

Comments
ย (0)