-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2416.cpp
More file actions
52 lines (51 loc) · 1.26 KB
/
2416.cpp
File metadata and controls
52 lines (51 loc) · 1.26 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
class TrieNode {
public:
TrieNode* children[26];
bool isEnd;
int numOfSubNodes;
TrieNode () {
memset(children, 0, sizeof(children));
isEnd = false;
numOfSubNodes = 0;
}
};
class Trie {
public:
TrieNode* root;
Trie () {
root = new TrieNode();
}
void insert(string& s) {
TrieNode* current = root;
for (auto& c : s) {
if (current->children[c - 'a'] == nullptr) {
current->children[c - 'a'] = new TrieNode();
}
current = current->children[c - 'a'];
current->numOfSubNodes++; // important
}
current->isEnd = true;
}
int traverse(string& s) {
int count = 0;
TrieNode* current = root;
for (auto& c : s) {
current = current->children[c - 'a'];
count += current->numOfSubNodes;
}
return count;
}
};
class Solution {
public:
vector<int> sumPrefixScores(vector<string>& words) {
Trie* trie = new Trie();
for (auto& word : words) trie->insert(word);
int n = words.size();
vector<int> res(n, 0);
for (int i = 0; i < n; ++i) {
res[i] = trie->traverse(words[i]);
}
return res;
}
};