-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2416-sum-of-prefix-scores-of-strings.cpp
63 lines (56 loc) · 1.23 KB
/
2416-sum-of-prefix-scores-of-strings.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
class trieNode {
public:
int cnt;
trieNode* child[26];
trieNode() {
cnt = 0;
fill(begin(child), end(child), nullptr);
}
};
class trie {
public:
trieNode* root;
trie() {
root = new trieNode();
}
int getIdx (char c) {
return c - 'a';
}
void insert(string& str) {
trieNode* node = root;
for (auto& i : str) {
int idx = getIdx(i);
if (!node->child[idx]) {
node->child[idx] = new trieNode();
}
node = node->child[idx];
node->cnt++;
}
}
int prefix(string& str) {
trieNode* node = root;
int cnt = 0;
for (auto& i : str) {
int idx = getIdx(i);
if (!node->child[idx]) return cnt;
node = node->child[idx];
cnt += node->cnt;
}
return cnt;
}
};
class Solution {
public:
vector<int> sumPrefixScores(vector<string>& words) {
trie tr;
for (auto& i : words) {
tr.insert(i);
}
int n = words.size();
vector<int> ans(n);
for (int i = 0; i < n; i++) {
ans[i] = tr.prefix(words[i]);
}
return ans;
}
};