Skip to content

Commit d676e73

Browse files
committed
implement-trie-prefix-tree solution
1 parent 4844d5d commit d676e73

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
var Trie = function() {
2+
this.root = {}; // ๋ฃจํŠธ๋Š” ๋นˆ ๊ฐ์ฒด๋กœ ์‹œ์ž‘
3+
};
4+
5+
/**
6+
* @param {string} word
7+
* @return {void}
8+
*/
9+
Trie.prototype.insert = function(word) {
10+
let node = this.root;
11+
for (let ch of word) {
12+
if (!node[ch]) node[ch] = {};
13+
node = node[ch];
14+
}
15+
node.isEnd = true; // ๋‹จ์–ด์˜ ๋์„ ํ‘œ์‹œ
16+
};
17+
18+
/**
19+
* @param {string} word
20+
* @return {boolean}
21+
*/
22+
Trie.prototype.search = function(word) {
23+
let node = this.root;
24+
for (let ch of word) {
25+
if (!node[ch]) return false;
26+
node = node[ch];
27+
}
28+
return node.isEnd === true; // ๋‹จ์–ด์˜ ๋์ด์–ด์•ผ๋งŒ true
29+
};
30+
31+
/**
32+
* @param {string} prefix
33+
* @return {boolean}
34+
*/
35+
Trie.prototype.startsWith = function(prefix) {
36+
let node = this.root;
37+
for (let ch of prefix) {
38+
if (!node[ch]) return false;
39+
node = node[ch];
40+
}
41+
return true; // ์ ‘๋‘์‚ฌ๋งŒ ๋งค์นญ๋˜๋ฉด true
42+
};

0 commit comments

Comments
ย (0)