-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1804-implement-trie-ii-prefix-tree.js
More file actions
81 lines (76 loc) · 2.16 KB
/
1804-implement-trie-ii-prefix-tree.js
File metadata and controls
81 lines (76 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* 1804. Implement Trie II (Prefix Tree)
* https://leetcode.com/problems/implement-trie-ii-prefix-tree/
* Difficulty: Medium
*
* A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store
* and retrieve keys in a dataset of strings. There are various applications of this data structure,
* such as autocomplete and spellchecker.
*
* Implement the Trie class:
* - Trie() Initializes the trie object.
* - void insert(String word) Inserts the string word into the trie.
* - int countWordsEqualTo(String word) Returns the number of instances of the string word in the
* trie.
* - int countWordsStartingWith(String prefix) Returns the number of strings in the trie that have
* the string prefix as a prefix.
* - void erase(String word) Erases the string word from the trie.
*/
var Trie = function() {
this.root = { children: {}, wordCount: 0, prefixCount: 0 };
};
/**
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function(word) {
let currentNode = this.root;
for (const char of word) {
if (!currentNode.children[char]) {
currentNode.children[char] = { children: {}, wordCount: 0, prefixCount: 0 };
}
currentNode = currentNode.children[char];
currentNode.prefixCount++;
}
currentNode.wordCount++;
};
/**
* @param {string} word
* @return {number}
*/
Trie.prototype.countWordsEqualTo = function(word) {
let currentNode = this.root;
for (const char of word) {
if (!currentNode.children[char]) {
return 0;
}
currentNode = currentNode.children[char];
}
return currentNode.wordCount;
};
/**
* @param {string} prefix
* @return {number}
*/
Trie.prototype.countWordsStartingWith = function(prefix) {
let currentNode = this.root;
for (const char of prefix) {
if (!currentNode.children[char]) {
return 0;
}
currentNode = currentNode.children[char];
}
return currentNode.prefixCount;
};
/**
* @param {string} word
* @return {void}
*/
Trie.prototype.erase = function(word) {
let currentNode = this.root;
for (const char of word) {
currentNode = currentNode.children[char];
currentNode.prefixCount--;
}
currentNode.wordCount--;
};