forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
implement-trie-ii-prefix-tree.cpp
77 lines (70 loc) · 1.91 KB
/
implement-trie-ii-prefix-tree.cpp
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
// Time: ctor: O(1)
// insert: O(n)
// count_word: O(n)
// count_prefix: O(n)
// erase: O(n)
// Space: O(t), t is the number of nodes in trie
class TrieNode {
public:
TrieNode() : children(26) {}
vector<unique_ptr<TrieNode>> children;
int pcnt = 0;
int cnt = 0;
};
class Trie {
public:
Trie() {
trie_ = make_unique<TrieNode>();
}
void insert(string word) {
auto curr = trie_.get();
++curr->pcnt;
for (const auto& c : word) {
if (curr->children[c - 'a'] == nullptr) {
curr->children[c - 'a'] = make_unique<TrieNode>();
}
curr = curr->children[c - 'a'].get();
++curr->pcnt;
}
++curr->cnt;
}
int countWordsEqualTo(string word) {
auto curr = trie_.get();
for (const auto& c : word) {
if (curr->children[c - 'a'] == nullptr) {
return 0;
}
curr = curr->children[c - 'a'].get();
}
return curr->cnt;
}
int countWordsStartingWith(string prefix) {
auto curr = trie_.get();
for (const auto& c : prefix) {
if (curr->children[c - 'a'] == nullptr) {
return 0;
}
curr = curr->children[c - 'a'].get();
}
return curr->pcnt;
}
void erase(string word) {
int cnt = countWordsEqualTo(word);
if (!cnt) {
return;
}
auto curr = trie_.get();
--curr->pcnt;
for (const auto& c : word) {
if (curr->children[c - 'a']->pcnt == 1) {
curr->children[c - 'a'].reset(); // delete all unused nodes
return;
}
curr = curr->children[c - 'a'].get();
--curr->pcnt;
}
--curr->cnt;
}
private:
unique_ptr<TrieNode> trie_;
};