-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path677.java
More file actions
90 lines (79 loc) · 2.39 KB
/
677.java
File metadata and controls
90 lines (79 loc) · 2.39 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
__________________________________________________________________________________________________
sample 45 ms submission
class MapSum {
TrieNode root;
/** Initialize your data structure here. */
public MapSum() {
root = new TrieNode();
}
public void insert(String key, int val) {
TrieNode node = root;
for (int i = 0; i < key.length(); i++) {
char c = key.charAt(i);
if (node.children[c-'a'] == null) {
node.children[c-'a'] = new TrieNode();
}
node = node.children[c-'a'];
}
node.isEnd = true;
node.val = val;
}
public int sum(String prefix) {
TrieNode node = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (node.children[c-'a'] == null) return 0;
node = node.children[c-'a'];
}
return sumFromHere(node);
}
int sumFromHere(TrieNode node) {
int sum = 0;
if (node.isEnd) sum += node.val;
for (TrieNode child: node.children) {
if (child != null) sum += sumFromHere(child);
}
return sum;
}
class TrieNode {
boolean isEnd;
int val; // only used when isEnd = true;
TrieNode[] children = new TrieNode[26];
public TrieNode () {
}
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/
__________________________________________________________________________________________________
sample 36760 kb submission
class MapSum {
Map<String, Integer> map;
/** Initialize your data structure here. */
public MapSum() {
map = new HashMap<>();
}
public void insert(String key, int val) {
map.put(key, val);
}
public int sum(String prefix) {
int ans = 0;
for (String key : map.keySet()) {
if (key.startsWith(prefix)) {
ans += map.get(key);
}
}
return ans;
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/
__________________________________________________________________________________________________