-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
59 lines (49 loc) · 1.5 KB
/
Solution.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
class MapSum {
private class TrieNode {
public Map<Character, TrieNode> children;
public Integer val;
public TrieNode () {
children = new HashMap<Character, TrieNode>();
val = null;
}
}
private TrieNode root;
/** Initialize your data structure here. */
public MapSum() {
root = new TrieNode();
}
public void insert(String key, int val) {
TrieNode node = root;
for (char c : key.toCharArray()) {
if (node.children.get(c) == null) {
node.children.put(c, new TrieNode());
}
node = node.children.get(c);
}
node.val = val;
}
public int sum(String prefix) {
int sum = 0;
TrieNode node = root;
for (char c : prefix.toCharArray()) {
if (node.children.get(c) == null) {
return 0;
}
node = node.children.get(c);
}
sum += node.val == null ? 0 : node.val;
List<TrieNode> stack = new ArrayList<TrieNode>(node.children.values());
while (stack.size() > 0) {
node = stack.remove(0);
stack.addAll(node.children.values());
sum += node.val == null ? 0 : node.val;
}
return sum;
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/