Skip to content

Commit bd296cc

Browse files
committed
Time: 567 ms (67.58%), Space: 703.9 MB (74.56%) - LeetHub
1 parent ba89022 commit bd296cc

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class trieNode {
2+
public:
3+
int cnt;
4+
trieNode* child[26];
5+
trieNode() {
6+
cnt = 0;
7+
fill(begin(child), end(child), nullptr);
8+
}
9+
};
10+
11+
class trie {
12+
public:
13+
trieNode* root;
14+
trie() {
15+
root = new trieNode();
16+
}
17+
18+
int getIdx (char c) {
19+
return c - 'a';
20+
}
21+
22+
void insert(string& str) {
23+
trieNode* node = root;
24+
for (auto& i : str) {
25+
int idx = getIdx(i);
26+
if (!node->child[idx]) {
27+
node->child[idx] = new trieNode();
28+
}
29+
node = node->child[idx];
30+
node->cnt++;
31+
}
32+
}
33+
34+
int prefix(string& str) {
35+
trieNode* node = root;
36+
int cnt = 0;
37+
for (auto& i : str) {
38+
int idx = getIdx(i);
39+
if (!node->child[idx]) return cnt;
40+
node = node->child[idx];
41+
cnt += node->cnt;
42+
}
43+
return cnt;
44+
}
45+
};
46+
47+
class Solution {
48+
public:
49+
vector<int> sumPrefixScores(vector<string>& words) {
50+
51+
trie tr;
52+
for (auto& i : words) {
53+
tr.insert(i);
54+
}
55+
56+
int n = words.size();
57+
vector<int> ans(n);
58+
for (int i = 0; i < n; i++) {
59+
ans[i] = tr.prefix(words[i]);
60+
}
61+
return ans;
62+
}
63+
};

0 commit comments

Comments
 (0)