Skip to content

Commit e7a77c7

Browse files
committed
implement trie prefix tree solution
1 parent 823887c commit e7a77c7

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
var TrieNode = function () {
2+
this.children = {};
3+
this.isEnd = false;
4+
}
5+
6+
var Trie = function () {
7+
this.root = new TrieNode();
8+
};
9+
10+
/**
11+
* @param {string} word
12+
* @return {void}
13+
*/
14+
Trie.prototype.insert = function (word) {
15+
let currentNode = this.root;
16+
for (let i = 0; i < word.length; i++) {
17+
let char = word[i];
18+
if (!currentNode.children[char]) {
19+
currentNode.children[char] = new TrieNode();
20+
21+
}
22+
currentNode = currentNode.children[char];
23+
}
24+
25+
currentNode.isEnd = true;
26+
};
27+
28+
/**
29+
* @param {string} word
30+
* @return {boolean}
31+
*/
32+
Trie.prototype.search = function (word) {
33+
let currentNode = this.root;
34+
for (let i = 0; i < word.length; i++) {
35+
let char = word[i];
36+
if (!currentNode.children[char]) {
37+
return false;
38+
}
39+
currentNode = currentNode.children[char];
40+
}
41+
return currentNode.isEnd;
42+
};
43+
44+
/**
45+
* @param {string} prefix
46+
* @return {boolean}
47+
*/
48+
Trie.prototype.startsWith = function (prefix) {
49+
let currentNode = this.root;
50+
for (let i = 0; i < prefix.length; i++) {
51+
let char = prefix[i];
52+
if (!currentNode.children[char]) {
53+
return false;
54+
}
55+
currentNode = currentNode.children[char];
56+
}
57+
return true;
58+
};
59+
60+
/**
61+
* Your Trie object will be instantiated and called as such:
62+
* var obj = new Trie()
63+
* obj.insert(word)
64+
* var param_2 = obj.search(word)
65+
* var param_3 = obj.startsWith(prefix)
66+
*/

0 commit comments

Comments
 (0)