Skip to content

Commit 388dbb5

Browse files
authored
Create 1804-implement-trie-ii-prefix-tree.js
1 parent b3394c8 commit 388dbb5

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

1804-implement-trie-ii-prefix-tree.js

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
class Node {
2+
constructor(val) {
3+
this.val = val
4+
this.cnt = 0
5+
this.children = {}
6+
this.wordCnt = 0
7+
}
8+
}
9+
10+
const Trie = function () {
11+
this.root = new Node(null)
12+
}
13+
14+
/**
15+
* @param {string} word
16+
* @return {void}
17+
*/
18+
Trie.prototype.insert = function (word) {
19+
let cur = this.root
20+
for(const ch of word) {
21+
if(cur.children[ch] == null) cur.children[ch] = new Node(ch)
22+
cur.children[ch].cnt++
23+
cur = cur.children[ch]
24+
}
25+
cur.wordCnt++
26+
}
27+
28+
/**
29+
* @param {string} word
30+
* @return {number}
31+
*/
32+
Trie.prototype.countWordsEqualTo = function (word) {
33+
let cur = this.root
34+
for(const ch of word) {
35+
if(cur.children[ch] == null) return 0
36+
cur = cur.children[ch]
37+
}
38+
return cur.wordCnt
39+
}
40+
41+
/**
42+
* @param {string} prefix
43+
* @return {number}
44+
*/
45+
Trie.prototype.countWordsStartingWith = function (prefix) {
46+
let cur = this.root
47+
for(const ch of prefix) {
48+
if(cur.children[ch] == null) return 0
49+
cur = cur.children[ch]
50+
}
51+
return cur.cnt
52+
}
53+
54+
/**
55+
* @param {string} word
56+
* @return {void}
57+
*/
58+
Trie.prototype.erase = function (word) {
59+
let cur = this.root
60+
for(const ch of word) {
61+
if(cur.children[ch] == null) break
62+
cur.children[ch].cnt--
63+
cur = cur.children[ch]
64+
}
65+
cur.wordCnt--
66+
}
67+
68+
/**
69+
* Your Trie object will be instantiated and called as such:
70+
* var obj = new Trie()
71+
* obj.insert(word)
72+
* var param_2 = obj.countWordsEqualTo(word)
73+
* var param_3 = obj.countWordsStartingWith(prefix)
74+
* obj.erase(word)
75+
*/

0 commit comments

Comments
 (0)