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.
classTrie:def__init__(self):self.children:List[Trie|None]=[None]*26self.val:int=0definsert(self,w:str,x:int):node=selfforcinw:idx=ord(c)-ord('a')ifnode.children[idx]isNone:node.children[idx]=Trie()node=node.children[idx]node.val+=xdefsearch(self,w:str)->int:node=selfforcinw:idx=ord(c)-ord('a')ifnode.children[idx]isNone:return0node=node.children[idx]returnnode.valclassMapSum:def__init__(self):self.d=defaultdict(int)self.tree=Trie()definsert(self,key:str,val:int)->None:x=val-self.d[key]self.d[key]=valself.tree.insert(key,x)defsum(self,prefix:str)->int:returnself.tree.search(prefix)# Your MapSum object will be instantiated and called as such:# obj = MapSum()# obj.insert(key,val)# param_2 = obj.sum(prefix)
classTrie{privateTrie[]children=newTrie[26];privateintval;publicvoidinsert(Stringw,intx){Trienode=this;for(inti=0;i<w.length();++i){intidx=w.charAt(i)-'a';if(node.children[idx]==null){node.children[idx]=newTrie();}node=node.children[idx];node.val+=x;}}publicintsearch(Stringw){Trienode=this;for(inti=0;i<w.length();++i){intidx=w.charAt(i)-'a';if(node.children[idx]==null){return0;}node=node.children[idx];}returnnode.val;}}classMapSum{privateMap<String,Integer>d=newHashMap<>();privateTrietrie=newTrie();publicMapSum(){}publicvoidinsert(Stringkey,intval){intx=val-d.getOrDefault(key,0);d.put(key,val);trie.insert(key,x);}publicintsum(Stringprefix){returntrie.search(prefix);}}/** * Your MapSum object will be instantiated and called as such: * MapSum obj = new MapSum(); * obj.insert(key,val); * int param_2 = obj.sum(prefix); */