1、题目描述
实现一个 MapSum 类,支持两个方法,insert 和 sum:
MapSum() 初始化 MapSum 对象
void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。
int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。
2、算法分析
使用Map集合的特性,keySet()获取Map集合中的所有键。
startsWith() 方法用于检测字符串是否以指定的前缀开始。
public boolean startsWith(String prefix, int toffset) 或 public boolean startsWith(String prefix)
3、代码实现
import java.util.*;
class MapSum {
private Map<String,Integer> map;
public MapSum() {
map = new HashMap<String,Integer>();
}
public void insert(String key, int val) {
map.put(key,val);
}
public int sum(String prefix) {
int kSum = 0;
Set<String> set = map.keySet();
for(String s:set){
if(s.startsWith(prefix)){
kSum = kSum + map.get(s);
}
}
return kSum;
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/