Skip to content

Commit f9c3bdf

Browse files
committed
implement-trie-prefix-tree
1 parent 484cede commit f9c3bdf

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* Trie(ํŠธ๋ผ์ด) ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ ๊ตฌํ˜„
3+
*
4+
* ์›๋ฆฌ: ํŠธ๋ผ์ด๋Š” ๋ฌธ์ž์—ด์„ ํšจ์œจ์ ์œผ๋กœ ์ €์žฅํ•˜๊ณ  ๊ฒ€์ƒ‰ํ•˜๊ธฐ ์œ„ํ•œ ํŠธ๋ฆฌ ๊ตฌ์กฐ
5+
* ๊ฐ ๋…ธ๋“œ๋Š” ํ•œ ๋ฌธ์ž๋ฅผ ๋‚˜ํƒ€๋‚ด๋ฉฐ, ๋ฃจํŠธ์—์„œ ํŠน์ • ๋…ธ๋“œ๊นŒ์ง€์˜ ๊ฒฝ๋กœ๊ฐ€ ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด์ด ๋œ๋‹ค
6+
* ๊ณตํ†ต ์ ‘๋‘์‚ฌ๋ฅผ ๊ณต์œ ํ•˜์—ฌ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์ ˆ์•ฝํ•˜๊ณ , ์ ‘๋‘์‚ฌ ๊ฒ€์ƒ‰์„ O(k) ์‹œ๊ฐ„์— ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ์Œ
7+
*/
8+
var Trie = function () {
9+
this.root = {}; // ๋ฃจํŠธ ๋…ธ๋“œ
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 char of word) {
20+
if (!node[char]) {
21+
// ์ฒ˜์Œ ๋“ค์–ด์˜ค๋Š” ๋‹จ์–ด์ผ ๊ฒฝ์šฐ, ์ƒˆ ํŠธ๋ฆฌ๊ตฌ์กฐ ์ƒ์„ฑ
22+
node[char] = {};
23+
}
24+
// ํ˜„์žฌ ๋‹จ์–ด ์œ„์น˜๋กœ ์ด๋™
25+
node = node[char];
26+
}
27+
node.isEnd = true; // ๋‹จ์–ด ๋ ํ‘œ์‹œ
28+
};
29+
30+
/**
31+
* @param {string} word
32+
* @return {boolean}
33+
*/
34+
Trie.prototype.search = function (word) {
35+
let node = this.traverse(word);
36+
return node !== null && node.isEnd === true;
37+
};
38+
39+
/**
40+
* @param {string} prefix
41+
* @return {boolean}
42+
*/
43+
Trie.prototype.startsWith = function (prefix) {
44+
return this.traverse(prefix) !== null;
45+
};
46+
47+
/**
48+
* ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์„ ๋”ฐ๋ผ ํŠธ๋ผ์ด๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ํ•จ์ˆ˜
49+
* @param {string} str - ํŠธ๋ผ์ด์—์„œ ํƒ์ƒ‰ํ•  ๋ฌธ์ž์—ด
50+
* @return {object|null} - ๋ฌธ์ž์—ด ๊ฒฝ๋กœ์˜ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ ๋˜๋Š” ๊ฒฝ๋กœ๊ฐ€ ์—†์œผ๋ฉด null
51+
*/
52+
Trie.prototype.traverse = function (str) {
53+
let node = this.root;
54+
55+
// ๋ฌธ์ž์—ด์˜ ๊ฐ ๋ฌธ์ž๋ฅผ ํ•˜๋‚˜์”ฉ ์ˆœํšŒ
56+
for (let char of str) {
57+
// ํ˜„์žฌ ๋ฌธ์ž์— ๋Œ€ํ•œ ๊ฒฝ๋กœ๊ฐ€ ์—†์œผ๋ฉด ํƒ์ƒ‰ ์‹คํŒจ
58+
if (!node[char]) {
59+
return null;
60+
}
61+
// ํ•ด๋‹น ๋ฌธ์ž์˜ ๋…ธ๋“œ๋กœ ์ด๋™ํ•˜์—ฌ ํƒ์ƒ‰ ๊ณ„์†
62+
node = node[char];
63+
}
64+
return node;
65+
};
66+
67+
/**
68+
* Your Trie object will be instantiated and called as such:
69+
* var obj = new Trie()
70+
* obj.insert(word)
71+
* var param_2 = obj.search(word)
72+
* var param_3 = obj.startsWith(prefix)
73+
*/

0 commit comments

Comments
ย (0)