-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day-232.cpp
63 lines (61 loc) · 1.49 KB
/
Day-232.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
class MapSum {
class Node{
public:
Node* node[30];
bool isEnd;
int num;
Node() {
for (int i=0; i<30; ++i) {
node[i] = nullptr;
}
isEnd = false;
num = 0;
}
};
Node *root;
public:
/** Initialize your data structure here. */
MapSum() {
root = new Node();
}
void insert(string key, int val) {
Node* temp = root;
for (auto&itr:key) {
if (temp -> node[itr-'a'] == nullptr) {
temp->node[itr-'a'] = new Node();
}
temp = temp->node[itr-'a'];
}
temp -> num = val;
temp -> isEnd = true;
}
int dfs(Node*temp) {
int res = 0;
if (temp == nullptr)return res;
if (temp-> isEnd) {
res += temp -> num;
}
for (auto itr: temp->node) {
res += dfs(itr);
}
return res;
}
int sum(string prefix) {
int res{};
Node*temp = root;
for (auto&itr:prefix) {
if (temp -> node[itr-'a'] != nullptr) {
temp = temp->node[itr-'a'];
} else {
return res;
}
}
return res + dfs(temp);
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/