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 res = 0;
for (String s : map.keySet()) {
if (s.startsWith(prefix)) {
res += map.get(s);
}
}
return res;
}
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/z1R5dt/solution/dan-ci-zhi-he-by-leetcode-solution-8vyo/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class MapSum {
Map<String, Integer> map;
Map<String, Integer> prefixmap;
public MapSum() {
map = new HashMap<>();
prefixmap = new HashMap<>();
}
public void insert(String key, int val) {
int delta = val - map.getOrDefault(key, 0);
map.put(key, val);
for (int i = 1; i <= key.length(); ++i) {
String currprefix = key.substring(0, i);
prefixmap.put(currprefix, prefixmap.getOrDefault(currprefix, 0) + delta);
}
}
public int sum(String prefix) {
return prefixmap.getOrDefault(prefix, 0);
}
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/z1R5dt/solution/dan-ci-zhi-he-by-leetcode-solution-8vyo/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。