Skip to content

Commit 2610d2f

Browse files
committed
trie
1 parent 7c1359b commit 2610d2f

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

dataStructure/trie/trie.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* Initialize your data structure here.
3+
*/
4+
const TrieNode = function (char) {
5+
this.val = char;
6+
this.map = new Map();
7+
this.isEnd = false;
8+
};
9+
10+
var Trie = function () {
11+
this.root = new TrieNode(null);
12+
};
13+
14+
/**
15+
* Inserts a word into the trie.
16+
* @param {string} word
17+
* @return {void}
18+
*/
19+
Trie.prototype.insert = function (word) {
20+
const charArr = word.split('');
21+
let pointer = this.root;
22+
for (let char of charArr) {
23+
if (!pointer.map.has(char)) {
24+
pointer.map.set(char, new TrieNode(char));
25+
}
26+
27+
pointer = pointer.map.get(char);
28+
}
29+
pointer.isEnd = true;
30+
};
31+
32+
/**
33+
* Returns if the word is in the trie.
34+
* @param {string} word
35+
* @return {boolean}
36+
*/
37+
Trie.prototype.search = function (word) {
38+
const charArr = word.split('');
39+
let pointer = this.root;
40+
for (let char of charArr) {
41+
if (!pointer.map.has(char)) {
42+
return false;
43+
}
44+
45+
pointer = pointer.map.get(char);
46+
}
47+
48+
return pointer.isEnd;
49+
};
50+
51+
/**
52+
* Returns if there is any word in the trie that starts with the given prefix.
53+
* @param {string} prefix
54+
* @return {boolean}
55+
*/
56+
Trie.prototype.startsWith = function (prefix) {
57+
const charArr = prefix.split('');
58+
let pointer = this.root;
59+
for (let char of charArr) {
60+
if (!pointer.map.has(char)) {
61+
return false;
62+
}
63+
64+
pointer = pointer.map.get(char);
65+
}
66+
67+
return true;
68+
};
69+
70+
/**
71+
* Your Trie object will be instantiated and called as such:
72+
* var obj = new Trie()
73+
* obj.insert(word)
74+
* var param_2 = obj.search(word)
75+
* var param_3 = obj.startsWith(prefix)
76+
*/

0 commit comments

Comments
 (0)