解题思路
利用HashMap存储键值对,利用keySet取出每个key,取出每个perfix为前缀的key对应的值即可
代码
class MapSum {
Map<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 ans = 0;
Set<String> set = map.keySet();
for (String key : set){
if (key.startsWith(prefix)){
ans += map.get(key);
}
}
return ans;
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/