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: Null Input: sum("ap"), Output: 3 Input: insert("app", 2), Output: Null Input: sum("ap"), Output: 5
实现MapSum 数据结构,其中包含两个方法insert和sum。insert是记录一个字符串-整数对。sum是求所有键值的前缀为prefix的对的数字和。使用unordered_map记录键值对。实现starts_with函数来判断是否是前缀。则insert和sum方法很容易就实现了。
代码:
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
}
void insert(string key, int val) {
pairs[key] = val;
}
int sum(string prefix) {
int res = 0;
for(auto p:pairs) {
if(starts_with(p.first, prefix)) {
res += p.second;
}
}
return res;
}
private:
unordered_map<string, int> pairs;
bool starts_with(string s, string t) {
return s.substr(0, t.size()) == t;
}
};