-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathMapSumPairs.cpp
67 lines (54 loc) · 1.4 KB
/
MapSumPairs.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
62
63
64
65
66
67
class MapSum {
public:
/** Initialize your data structure here. */
struct Node{
int val;
vector<Node*> child;
Node(int x=0){
for(int i = 0; i < 26; i++){
child.push_back(NULL);
}
val = x;
}
};
Node* head;
MapSum() {
head = new Node();
}
void insert(string key, int val) {
Node* curr = head;
for(int i = 0; i < key.size(); i++){
if(curr->child[key[i]-'a'] == NULL){
curr->child[key[i]-'a'] = new Node();
}
curr = curr->child[key[i]-'a'];
}
curr->val = val;
}
int getAns(Node* head){
if(!head){
return 0;
}
int ans = head->val;
for(int i = 0; i < 26; i++){
ans += getAns(head->child[i]);
}
return ans;
}
int sum(string prefix) {
Node* curr = head;
for(int i = 0; i < prefix.size(); i++){
if(curr->child[prefix[i]-'a'] == NULL){
return 0;
}
curr = curr->child[prefix[i]-'a'];
}
return getAns(curr);
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/