题意:通过Trie求前缀和,相同字符串取最新的值。
class TrieNode{
public:
int val;
TrieNode *nex[26];
TrieNode(){
val = 0;
for(int i = 0; i < 26; ++i){
nex[i] = NULL;
}
}
};
class MapSum {
public:
TrieNode *root;
map<string, int> mp;
/** Initialize your data structure here. */
MapSum() {
root = new TrieNode();
}
void insert(string key, int val) {
TrieNode *p = root;
int len = key.size();
int add = val - mp[key];
for(int i = 0; i < len; ++i){
if(p -> nex[key[i] - ‘a‘] == NULL){
p -> nex[key[i] - ‘a‘] = new TrieNode();
}
p = p -> nex[key[i] - ‘a‘];
p -> val += add;
}
mp[key] = val;
}
int sum(string prefix) {
TrieNode *p = root;
int len = prefix.size();
for(int i = 0; i < len; ++i){
if(p -> nex[prefix[i] - ‘a‘] == NULL) return 0;
p = p -> nex[prefix[i] - ‘a‘];
}
return p -> val;
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/
677. Map Sum Pairs(通过Trie求前缀和)
原文:https://www.cnblogs.com/tyty-Somnuspoppy/p/12621162.html