Skip to content

Commit 6689ad3

Browse files
committed
implement-trie-prefix-tree solved
1 parent a749ba2 commit 6689ad3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

implement-trie-prefix-tree/hsskey.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class TrieNode {
2+
constructor() {
3+
this.children = {};
4+
this.isEndOfWord = false;
5+
}
6+
}
7+
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+
for (const char of word) {
19+
if (!node.children[char]) {
20+
node.children[char] = new TrieNode();
21+
}
22+
node = node.children[char];
23+
}
24+
node.isEndOfWord = true;
25+
};
26+
27+
/**
28+
* @param {string} word
29+
* @return {boolean}
30+
*/
31+
Trie.prototype.search = function(word) {
32+
let node = this.root;
33+
for (const char of word) {
34+
if (!node.children[char]) return false;
35+
node = node.children[char];
36+
}
37+
return node.isEndOfWord;
38+
};
39+
40+
/**
41+
* @param {string} prefix
42+
* @return {boolean}
43+
*/
44+
Trie.prototype.startsWith = function(prefix) {
45+
let node = this.root;
46+
for (const char of prefix) {
47+
if (!node.children[char]) return false;
48+
node = node.children[char];
49+
}
50+
return true;
51+
};

0 commit comments

Comments
 (0)