在原始Tire树的基础上改造,每个节点维护后面的所有后缀的value之和。用一个HashMap计数处理重复。
struct TrieNode {
int val;
TrieNode * next[26];
TrieNode() {
this->val = 0;
for (int i = 0; i < 26; ++i) {
this->next[i] = nullptr;
}
}
};
class MapSum {
private:
TrieNode* root;
unordered_map<string, int> cnt;
public:
MapSum() {
root = new TrieNode();
}
void insert(string key, int val) {
int mines = (cnt.count(key) ? cnt[key] : 0);
cnt[key] = val;
TrieNode* node = root;
for (auto c : key) {
if(node->next[c - 'a'] == nullptr) {
node->next[c - 'a'] = new TrieNode();
}
node = node->next[c - 'a'