-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathMapSumPairs
36 lines (28 loc) · 829 Bytes
/
MapSumPairs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class MapSum {
Map<String,Integer> map;
Map<String,Integer> score;
/** Initialize your data structure here. */
public MapSum() {
map = new HashMap();
score = new HashMap();
}
public void insert(String key, int val) {
int delta = val - map.getOrDefault(key,0);
map.put(key,val);
String prefix="";
for(char c:key.toCharArray())
{
prefix+=c;
score.put(prefix, score.getOrDefault(prefix,0)+delta);
}
}
public int sum(String prefix) {
return score.getOrDefault(prefix,score.getOrDefault(prefix,0));
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/