Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the MapSum class:
MapSum() Initializes the MapSum object.
void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
int sum(string prefix) Returns the sum of all the pairs’ value whose key starts with the prefix.
classMapSum { public: structTrieNode { int value; vector<TrieNode*> children; TrieNode() { value = 0; children = vector<TrieNode*>(26, nullptr); } };
TrieNode* root;
MapSum() { root = newTrieNode(); }
voidinsert(string key, int val){ TrieNode* head = root; for (char c : key) { if (head->children[c - 'a'] == nullptr) { head->children[c - 'a'] = newTrieNode(); } head = head->children[c - 'a']; } head->value = val; }
intsum(string prefix){ TrieNode* head = root; for (char c : prefix) { if (head->children[c - 'a'] == nullptr) { return0; } head = head->children[c - 'a']; } returntraverse(head); }
inttraverse(TrieNode* head){ if (head == nullptr) { return0; } int sum = 0; for (TrieNode* child : head->children) { sum += traverse(child); } return sum + head->value; } };
/** * Your MapSum object will be instantiated and called as such: * MapSum* obj = new MapSum(); * obj->insert(key,val); * int param_2 = obj->sum(prefix); */