-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
61 lines (53 loc) · 1.14 KB
/
Solution.cpp
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
class Trie {
public:
Trie()
: children(26, nullptr) {
}
void insert(string& w, int x) {
Trie* node = this;
for (char c : w) {
c -= 'a';
if (!node->children[c]) {
node->children[c] = new Trie();
}
node = node->children[c];
node->val += x;
}
}
int search(string& w) {
Trie* node = this;
for (char c : w) {
c -= 'a';
if (!node->children[c]) {
return 0;
}
node = node->children[c];
}
return node->val;
}
private:
vector<Trie*> children;
int val = 0;
};
class MapSum {
public:
MapSum() {
}
void insert(string key, int val) {
int x = val - d[key];
d[key] = val;
trie->insert(key, x);
}
int sum(string prefix) {
return trie->search(prefix);
}
private:
unordered_map<string, int> d;
Trie* trie = new Trie();
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/