思路:初始化为HashMap,对每个键值对进行存储,搜索给定的前缀时,遍历HashMap中的key,如果包含前缀,就对其value进行相加。
代码:
class MapSum {
HashMap<String,Integer> map;
public MapSum() {
map = new HashMap<>();
}
public void insert(String key, int val) {
map.put(key,val);
}
public int sum(String prefix) {
int s=0;
for(String key:map.keySet()){
if(key.indexOf(prefix)==0) s+=map.get(key);
}
return s;
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/