题目
难度 Medium
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
实现思路
题目就是考map的插入和查找以及string的一些用法。可以给MapSum类设一个<string,int>类型的map,然后调用map的[ ]下标操作实现题目要求的insert函数。
注意: 如果使用insert函数,当key已经存在时,map的insert函数不会创建新的该key,也不会修改该key的value,因此如果用map的insert函数实现需要判断该key是否已经存在;但是如果用[ ]访问下标符号来进行插入,比如a[key]=value;如果key已经存在就是修改该键值,如果key不存在就创建一个并把value赋值给该键值。
而sum函数则利用string的find函数,查找该字符串中找到的指定字符串的位置,如果返回的位置是0说明指定字符串为该字符串的前缀。
利用map按字典序排列的原理可以加快一点效率。
实现代码
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
//do nothing
}
void insert(string key, int val) {
// 若利用map的insert函数要注意key是否已存在问题
Map[key] = val;
}
int sum(string prefix) {
int summ = 0;
for (auto it = Map.begin(); it != Map.end(); it++) {
// 如果是前缀
if ((it->first).find(prefix.c_str()) == 0) {
summ += it->second;
// 利用map按字典序排列的原理,符合前缀要求的字符串应该是连续排列的
// 若该字符串的前缀不是prefix,且summ也不为0
// 则表明前缀为prefix的字符串已查找完毕
} else if (summ != 0) {
break;
}
}
return summ;
}
private:
map<string, int> Map;
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/