/
MapSumPairs.java
68 lines (55 loc) · 1.67 KB
/
MapSumPairs.java
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// https://leetcode.com/problems/map-sum-pairs/
class MapSum {
// Prefix trie
TrieNode head, t;
Map<String, Integer> values;
public MapSum() {
head = new TrieNode();
t = head;
values = new HashMap<>();
}
private void insertIntoTrie(String word) {
//System.out.println("Inserting " + word);
for (char c: word.toCharArray()) {
if (t.children[c - 'a'] == null) {
t.children[c - 'a'] = new TrieNode();
}
t = t.children[c - 'a'];
t.words.add(word);
}
//System.out.println("Added: new set = " + t.words);
t = head;
}
public void insert(String key, int val) {
values.put(key, val);
insertIntoTrie(key);
}
public int sum(String prefix) {
//System.out.println("Sum = " + prefix);
for (char c: prefix.toCharArray()) {
if (t.children[c - 'a'] == null) {
// It is important that we reset our to head here
t = head;
return 0;
}
t = t.children[c - 'a'];
}
int sum = 0;
for (String word: t.words) {
sum += values.get(word);
}
// Even after search is successful, we reset t
t = head;
return sum;
}
class TrieNode {
TrieNode[] children = new TrieNode[26];
Set<String> words = new HashSet<>();
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/