Skip to content

Commit 8601acf

Browse files
committed
Added implementTrie solution
1 parent 96a0c39 commit 8601acf

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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 char of word) {
12+
if (!node[char]) {
13+
node[char] = {};
14+
}
15+
node = node[char];
16+
}
17+
node.isEndOfWord = true;
18+
};
19+
20+
/**
21+
* @param {string} word
22+
* @return {boolean}
23+
*/
24+
Trie.prototype.search = function (word) {
25+
let node = this.root;
26+
for (let char of word) {
27+
if (!node[char]) {
28+
return false;
29+
}
30+
node = node[char];
31+
}
32+
return node.isEndOfWord === true;
33+
};
34+
35+
/**
36+
* @param {string} prefix
37+
* @return {boolean}
38+
*/
39+
Trie.prototype.startsWith = function (prefix) {
40+
let node = this.root;
41+
for (let char of prefix) {
42+
if (!node[char]) {
43+
return false;
44+
}
45+
node = node[char];
46+
}
47+
return true;
48+
};
49+
50+
// TC: O(n)
51+
// SC: O(n)

0 commit comments

Comments
 (0)