Skip to content

Commit 1c8afe9

Browse files
committed
solve: implement trie prefix tree
1 parent 857452b commit 1c8afe9

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

implement-trie-prefix-tree/wogha95.js

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
function Node() {
2+
this.value = null;
3+
this.wordGraph = new Map();
4+
}
5+
6+
var Trie = function () {
7+
this.wordGraph = new Map();
8+
};
9+
10+
/**
11+
* TC: O(W)
12+
* SC: O(W)
13+
* W: word.length
14+
*/
15+
16+
/**
17+
* @param {string} word
18+
* @return {void}
19+
*/
20+
Trie.prototype.insert = function (word) {
21+
let pointer = this;
22+
for (const w of word) {
23+
if (!pointer.wordGraph.has(w)) {
24+
pointer.wordGraph.set(w, new Node());
25+
}
26+
pointer = pointer.wordGraph.get(w);
27+
}
28+
pointer.value = word;
29+
};
30+
31+
/**
32+
* TC: O(W)
33+
* SC: O(1)
34+
* W: word.length
35+
*/
36+
37+
/**
38+
* @param {string} word
39+
* @return {boolean}
40+
*/
41+
Trie.prototype.search = function (word) {
42+
let pointer = this;
43+
for (const w of word) {
44+
if (!pointer.wordGraph.has(w)) {
45+
return false;
46+
} else {
47+
pointer = pointer.wordGraph.get(w);
48+
}
49+
}
50+
return pointer.value === word;
51+
};
52+
53+
/**
54+
* TC: O(P)
55+
* SC: O(1)
56+
* P:prefix.length
57+
*/
58+
59+
/**
60+
* @param {string} prefix
61+
* @return {boolean}
62+
*/
63+
Trie.prototype.startsWith = function (prefix) {
64+
let pointer = this;
65+
for (const p of prefix) {
66+
if (!pointer.wordGraph.has(p)) {
67+
return false;
68+
} else {
69+
pointer = pointer.wordGraph.get(p);
70+
}
71+
}
72+
return true;
73+
};
74+
75+
/**
76+
* Your Trie object will be instantiated and called as such:
77+
* var obj = new Trie()
78+
* obj.insert(word)
79+
* var param_2 = obj.search(word)
80+
* var param_3 = obj.startsWith(prefix)
81+
*/

0 commit comments

Comments
 (0)