Skip to content

Commit 2c6c1d7

Browse files
committed
Implement Trie (Prefix Tree) solution
1 parent 6530354 commit 2c6c1d7

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// TrieNode 클래슀 μ •μ˜: 트라이의 각 λ…Έλ“œλ₯Ό ν‘œν˜„
2+
var TrieNode = function () {
3+
this.children = new Map(); // μžμ‹ λ…Έλ“œλ₯Ό Map으둜 μ €μž₯
4+
this.isEnd = false; // λ‹¨μ–΄μ˜ 끝을 ν‘œμ‹œν•˜λŠ” ν”Œλž˜κ·Έ
5+
};
6+
7+
// Trie 클래슀 μ •μ˜: 트라이 자료ꡬ쑰λ₯Ό ν‘œν˜„
8+
var Trie = function () {
9+
this.root = new TrieNode(); // 루트 λ…Έλ“œ
10+
};
11+
12+
/**
13+
* @param {string} word
14+
* @return {void}
15+
*/
16+
Trie.prototype.insert = function (word) {
17+
let node = this.root; // ν˜„μž¬ λ…Έλ“œλ₯Ό 루트둜 μ΄ˆκΈ°ν™”
18+
19+
for (let i = 0; i < word.length; i++) {
20+
const char = word[i]; // ν˜„μž¬ 문자
21+
22+
// ν˜„μž¬ λ¬Έμžμ— λŒ€ν•œ μžμ‹ λ…Έλ“œκ°€ μ—†μœΌλ©΄ μƒˆλ‘œ 생성
23+
if (!node.children.has(char)) {
24+
node.children.set(char, new TrieNode());
25+
}
26+
27+
// λ‹€μŒ μžμ‹ λ…Έλ“œλ‘œ 이동
28+
node = node.children.get(char);
29+
}
30+
node.isEnd = true; // λ‹¨μ–΄μ˜ 끝을 ν‘œμ‹œ
31+
};
32+
33+
/**
34+
* @param {string} word
35+
* @return {boolean}
36+
*/
37+
Trie.prototype.search = function (word) {
38+
const node = this._searchPrefix(word); // μ£Όμ–΄μ§„ λ‹¨μ–΄μ˜ λ…Έλ“œλ₯Ό 찾음
39+
return node !== null && node.isEnd === true; // κ²½λ‘œκ°€ μ‘΄μž¬ν•˜κ³ , λ§ˆμ§€λ§‰ λ…Έλ“œκ°€ λ‹¨μ–΄μ˜ 끝인지 확인
40+
};
41+
42+
/**
43+
* @param {string} prefix
44+
* @return {boolean}
45+
*/
46+
Trie.prototype.startsWith = function (prefix) {
47+
return this._searchPrefix(prefix) !== null; // κ²½λ‘œκ°€ μ‘΄μž¬ν•˜λŠ”μ§€λ§Œ 확인
48+
};
49+
50+
/**
51+
* 헬퍼 λ©”μ„œλ“œ: μ£Όμ–΄μ§„ 접두사에 λŒ€ν•œ 경둜λ₯Ό μ°ΎλŠ” λ©”μ„œλ“œ
52+
* @param {string} str
53+
* @return {TrieNode|null} 경둜의 λ§ˆμ§€λ§‰ λ…Έλ“œ λ˜λŠ” null
54+
* @private
55+
*/
56+
Trie.prototype._searchPrefix = function (str) {
57+
let node = this.root; // ν˜„μž¬ λ…Έλ“œλ₯Ό 루트둜 μ΄ˆκΈ°ν™”
58+
59+
// μ£Όμ–΄μ§„ λ¬Έμžμ—΄μ˜ 각 λ¬Έμžμ— λŒ€ν•΄ λ…Έλ“œ 탐색
60+
for (let i = 0; i < str.length; i++) {
61+
const char = str[i]; // ν˜„μž¬ 문자
62+
63+
// ν˜„μž¬ λ¬Έμžμ— λŒ€ν•œ μžμ‹ λ…Έλ“œκ°€ μ—†μœΌλ©΄ null 리턴
64+
if (!node.children.has(char)) {
65+
return null;
66+
}
67+
68+
// λ‹€μŒ μžμ‹ λ…Έλ“œλ‘œ 이동
69+
node = node.children.get(char);
70+
}
71+
return node; // 경둜의 λ§ˆμ§€λ§‰ λ…Έλ“œ λ°˜ν™˜
72+
};
73+
/**
74+
* Your Trie object will be instantiated and called as such:
75+
* var obj = new Trie()
76+
* obj.insert(word)
77+
* var param_2 = obj.search(word)
78+
* var param_3 = obj.startsWith(prefix)
79+
*/

0 commit comments

Comments
Β (0)