forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.cpp
45 lines (41 loc) · 928 Bytes
/
Solution2.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
class Trie {
public:
Trie()
: children(26)
, cnt(0) {}
void insert(string w) {
Trie* node = this;
for (auto& c : w) {
int i = c - 'a';
if (!node->children[i]) {
node->children[i] = new Trie();
}
node = node->children[i];
++node->cnt;
}
}
int search(string pref) {
Trie* node = this;
for (auto& c : pref) {
int i = c - 'a';
if (!node->children[i]) {
return 0;
}
node = node->children[i];
}
return node->cnt;
}
private:
vector<Trie*> children;
int cnt;
};
class Solution {
public:
int prefixCount(vector<string>& words, string pref) {
Trie* tree = new Trie();
for (auto& w : words) {
tree->insert(w);
}
return tree->search(pref);
}
};