-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
count-prefix-and-suffix-pairs-ii.cpp
48 lines (43 loc) · 1.09 KB
/
count-prefix-and-suffix-pairs-ii.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
// Time: O(n * l)
// Space: O(t)
// trie
class Solution {
private:
class Trie {
public:
Trie()
: nodes_() {
new_node();
}
int add(const string& w) {
int result = 0, curr = 0;
for (int i = 0; i < size(w); ++i) {
const int k = (w[i] - 'a') * 26 + (w[size(w) - 1 - i] - 'a');
if (!nodes_[curr].count(k)) {
nodes_[curr][k] = new_node();
}
curr = nodes_[curr][k];
result += cnts_[curr];
}
++cnts_[curr];
return result;
}
private:
int new_node() {
nodes_.emplace_back();
cnts_.emplace_back(0);
return size(nodes_) - 1;
}
vector<unordered_map<int, int>> nodes_;
vector<int> cnts_;
};
public:
long long countPrefixSuffixPairs(vector<string>& words) {
int64_t result = 0;
Trie trie;
for (const auto& w : words) {
result += trie.add(w);
}
return result;
}
};