-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cs
53 lines (46 loc) · 1.26 KB
/
Solution.cs
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
public class Trie {
private Trie[] children = new Trie[26];
private int val;
public void Insert(string w, int x) {
Trie node = this;
for (int i = 0; i < w.Length; ++i) {
int idx = w[i] - 'a';
if (node.children[idx] == null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
node.val += x;
}
}
public int Search(string w) {
Trie node = this;
for (int i = 0; i < w.Length; ++i) {
int idx = w[i] - 'a';
if (node.children[idx] == null) {
return 0;
}
node = node.children[idx];
}
return node.val;
}
}
public class MapSum {
private Dictionary<string, int> d = new Dictionary<string, int>();
private Trie trie = new Trie();
public MapSum() {
}
public void Insert(string key, int val) {
int x = val - (d.ContainsKey(key) ? d[key] : 0);
d[key] = val;
trie.Insert(key, x);
}
public int Sum(string prefix) {
return trie.Search(prefix);
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.Insert(key,val);
* int param_2 = obj.Sum(prefix);
*/