typedefstructNode { structNode *next[26]; int val; int sum;
Node() { for (int i = 0; i < 26; i++) { next[i] = nullptr; this->val = 0; this->sum = 0; } }; } Node;
classMapSum { public: Node *root;
MapSum() { root = newNode(); }
voidinsert(string key, int val) { Node *now = root; for (int i = 0; i < key.length(); i++) { int keyNum = key[i] - 'a'; if (now->next[keyNum] == nullptr) { now->next[keyNum] = newNode(); } now = now->next[keyNum]; } if (now != nullptr) { if (now->val != val) { int diff = val - now->val; now->val = val; Node *newNow = root; newNow->sum += diff; for (int i = 0; i < key.length(); i++) { int keyNum = key[i] - 'a'; newNow = newNow->next[keyNum]; newNow->sum += diff; } } } }
intsum(string prefix) { Node *now = root; for (int i = 0; i < prefix.length(); i++) { int keyNum = prefix[i] - 'a'; if (now->next[keyNum] == nullptr) { return0; } now = now->next[keyNum]; }
return now->sum; } };
/** * Your MapSum object will be instantiated and called as such: * MapSum* obj = new MapSum(); * obj->insert(key,val); * int param_2 = obj->sum(prefix); */