Map Sum Pairs LeetCode solution in Java

1
class MapSum {
2
private Map<String, Integer> map;
3
private Map<String, Integer> words;
4

5
public MapSum() {
6
this.map = new HashMap<>();
7
this.words = new HashMap<>();
8
}
9

10
public void insert(String key, int val) {
11
Integer lookup = this.words.getOrDefault(key, null);
12
int diff;
13
if (lookup == null) diff = val;
14
else diff = val - lookup;
15

16
int k = key.length();
17

18
StringBuilder sb = new StringBuilder();
19
for (int i = 0; i < k; i++) {
20
sb.append(key.charAt(i));
21

22
String prefix = sb.toString();
23
map.put(prefix, map.getOrDefault(prefix, 0) + diff);
24
}
25

26
this.words.put(key, val);
27
}
28

29
public int sum(String prefix) {
30
return this.map.getOrDefault(prefix, 0);
31
}
32
}
33

34
/**
35
* Your MapSum object will be instantiated and called as such: MapSum obj = new MapSum();
36
* obj.insert(key,val); int param_2 = obj.sum(prefix);
37
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0