const int N = 1000010;
int son[N][26] = {0}, cnt[N] = {0}, idx = 0;
class Solution {
public:
void insert(string& s)
{
int p = 0;
for(auto&& c : s)
{
int u = c - 'a';
if(!son[p][u])
son[p][u] = ++ idx;
p = son[p][u];
cnt[p] ++;
}
}
int query(string &s)
{
int res = 0;
int p = 0;
for(auto&& c : s)
{
int u = c - 'a';
if(!son[p][u]) return res;
p = son[p][u];
res += cnt[p];
}
return res;
}
vector<int> sumPrefixScores(vector<string>& words) {
memset(son, 0, sizeof son);
memset(cnt, 0, sizeof cnt);
idx = 0;
for(auto&& w : words)
insert(w);
int n = words.size();
vector<int> res(n);
for(int i = 0; i < n; i ++)
res[i] = query(words[i]);
return res;
}
};
哈希
typedef unsigned long long ULL;
class Solution {
public:
ULL P = 131;
vector<int> sumPrefixScores(vector<string>& words) {
unordered_map<ULL, int> cnt;
for(auto&& w : words)
{
ULL hash = 0;
for(int i = 0; i < w.size(); i ++)
{
hash = hash * P + w[i];
cnt[hash] ++;
}
}
vector<int> res(words.size());
for(int j = 0; j < words.size(); j ++)
{
ULL hash = 0;
string& w = words[j];
for(int i = 0; i < w.size(); i ++)
{
hash = hash * P + w[i];
res[j] += cnt[hash];
}
}
return res;
}
};