-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
74 lines (63 loc) · 1.38 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <algorithm>
#include <array>
#include <bitset>
#include <climits>
#include <functional>
#include <iostream>
#include <memory>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
struct TrieNode {
bool isWord;
int32_t count;
std::array<TrieNode*, 26> children;
TrieNode() : isWord(false), count(0), children{} {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() : root(new TrieNode()) {}
void insert(const std::string word) {
TrieNode* iter = root;
for (const char& c : word) {
if (!iter->children[c - 'a']) {
iter->children[c - 'a'] = new TrieNode();
}
iter = iter->children[c - 'a'];
++iter->count;
}
iter->isWord = true;
return;
}
int countPrefixes(const std::string word) {
TrieNode* iter = root;
int count = 0;
for (const char& c : word) {
iter = iter->children[c - 'a'];
count += iter->count;
}
return count;
}
};
class Solution {
private:
public:
vector<int> sumPrefixScores(const vector<string>& words) {
Trie trie{};
for (const std::string& word : words) {
trie.insert(word);
}
const size_t n = words.size();
std::vector<int> count(n);
for (size_t i = 0; i < n; ++i) {
count[i] = trie.countPrefixes(words[i]);
}
return count;
}
};