Implement a MapSum class with insert
, and sum
methods.
For the method insert
, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.
For the method sum
, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix.
Example 1:
Input: insert("apple", 3), Output: NullInput: sum("ap"), Output: 3Input: insert("app", 2), Output: NullInput: sum("ap"), Output: 5
class MapSum { mapmp;public: /** Initialize your data structure here. */ MapSum() {} void insert(string key, int val) { mp[key]=val; } int sum(string prefix) { /* if (mp.find(prefix)==mp.end()){ return 0; } */ int res=0, n=prefix.size(); for(auto iter=mp.lower_bound(prefix);iter!=mp.end();++iter) { if(iter->first.substr(0,n)!=prefix) break; res+=iter->second; } return res; }};/** * Your MapSum object will be instantiated and called as such: * MapSum obj = new MapSum(); * obj.insert(key,val); * int param_2 = obj.sum(prefix); */
c++ map lower_bound upper_bound用法
运行 https://www.cnblogs.com/billin/archive/2011/09/01/2162102.html 一下代码就知道了
#include
输出
python代码
class MapSum(object): def __init__(self): """ Initialize your data structure here. """ self.d={} def insert(self, key, val): """ :type key: str :type val: int :rtype: void """ self.d[key]=val def sum(self, prefix): """ :type prefix: str :rtype: int """ return sum(self.d[i] for i in self.d if i.startswith(prefix)) # Your MapSum object will be instantiated and called as such:# obj = MapSum()# obj.insert(key,val)# param_2 = obj.sum(prefix)