-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
sum-of-prefix-scores-of-strings.cpp
55 lines (49 loc) · 1.32 KB
/
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
// Time: O(n * l), n is the number of words, l is the max length of words
// Space: O(t), t is the size of trie
// trie
class Solution {
public:
vector<int> sumPrefixScores(vector<string>& words) {
Trie trie;
for (const auto& w : words) {
trie.insert(w);
}
vector<int> result;
for (const auto& w : words) {
result.emplace_back(trie.query(w));
}
return result;
}
private:
class Trie {
public:
Trie() {
create_node();
}
void insert(const string& s) {
int curr = 0;
for (const auto& c : s) {
if (!nodes_[curr][c - 'a']) {
nodes_[curr][c - 'a'] = create_node();
}
curr = nodes_[curr][c - 'a'];
++nodes_[curr].back();
}
}
int query(const string& s) {
int result = 0, curr = 0;
for (const auto& c : s) {
curr = nodes_[curr][c - 'a'];
result += nodes_[curr].back();
}
return result;
}
private:
int create_node() {
nodes_.emplace_back(26 + 1);
return size(nodes_) - 1;
}
using TrieNode = vector<int>;
vector<TrieNode> nodes_;
};
};