-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapSum.java
More file actions
75 lines (63 loc) · 1.21 KB
/
MapSum.java
File metadata and controls
75 lines (63 loc) · 1.21 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
class MapSum
{
TrieMapSum _root = new TrieMapSum();
/** Initialize your data structure here. */
public MapSum()
{
}
public void insert( String key, int val )
{
_root.insert( key, val );
}
public int sum( String prefix )
{
return _root.lookup( prefix );
}
}
class TrieMapSum
{
int _val = 0, _sum = 0;
TrieMapSum[] _ch = new TrieMapSum[26];
void insert( String v, int val )
{
int oriVal = find( v );
TrieMapSum root = this;
root._sum += val - oriVal;
for ( char k : v.toCharArray() )
{
if ( root._ch[k - 'a'] == null )
root._ch[k - 'a'] = new TrieMapSum();
root = root._ch[k - 'a'];
root._sum += val - oriVal;
}
root._val = val;
}
int find( String v )
{
TrieMapSum root = this;
for ( char k : v.toCharArray() )
{
if ( root._ch[k - 'a'] == null )
return 0;
root = root._ch[k - 'a'];
}
return root._val;
}
int lookup( String v )
{
TrieMapSum root = this;
for ( char k : v.toCharArray() )
{
if ( root._ch[k - 'a'] == null )
return 0;
root = root._ch[k - 'a'];
}
return root._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);
*/