-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
66 lines (59 loc) · 1.39 KB
/
Solution.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
class Trie {
public:
Trie()
: children(26)
, v(0)
, pv(0) {
}
void insert(string word) {
Trie* node = this;
for (char c : word) {
c -= 'a';
if (!node->children[c]) {
node->children[c] = new Trie();
}
node = node->children[c];
++node->pv;
}
++node->v;
}
int countWordsEqualTo(string word) {
Trie* node = search(word);
return node ? node->v : 0;
}
int countWordsStartingWith(string prefix) {
Trie* node = search(prefix);
return node ? node->pv : 0;
}
void erase(string word) {
Trie* node = this;
for (char c : word) {
c -= 'a';
node = node->children[c];
--node->pv;
}
--node->v;
}
private:
vector<Trie*> children;
int v, pv;
Trie* search(string& word) {
Trie* node = this;
for (char c : word) {
c -= 'a';
if (!node->children[c]) {
return nullptr;
}
node = node->children[c];
}
return node;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* int param_2 = obj->countWordsEqualTo(word);
* int param_3 = obj->countWordsStartingWith(prefix);
* obj->erase(word);
*/