generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolution.cpp
50 lines (43 loc) · 1.02 KB
/
solution.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
#include <string>
#include <vector>
class Solution {
private:
struct Node {
int count{1};
Node* nexts[26] = {nullptr};
~Node() {
for (int i{0}; i < 26; ++i) {
if (nexts[i] != nullptr) delete nexts[i];
}
}
};
public:
std::vector<int> sumPrefixScores(std::vector<std::string>& words) {
Node root;
for (const auto& word : words) {
Node* node{&root};
for (const char* c{word.data()}; *c != 0; ++c) {
Node** next{node->nexts + *c - 'a'};
if (*next == nullptr) {
*next = new Node();
} else {
++((*next)->count);
}
node = *next;
}
}
std::vector<int> output{};
output.reserve(words.size());
for (const auto& word : words) {
int total{0};
Node* node{&root};
for (const char* c{word.data()}; *c != 0; ++c) {
Node** next{node->nexts + *c - 'a'};
total += (*next)->count;
node = *next;
}
output.push_back(total);
}
return output;
}
};