-
Notifications
You must be signed in to change notification settings - Fork 0
/
677.hpp
86 lines (73 loc) · 1.73 KB
/
677.hpp
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
76
77
78
79
80
81
82
83
84
85
86
#ifndef LEETCODE_677_HPP
#define LEETCODE_677_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
using namespace std;
struct TrieNode {
int val;
unordered_map<char, TrieNode *> children;
};
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
root = new TrieNode();
}
void insert(string key, int val) {
auto iter = root;
for (char c: key) {
if (iter->children.count(c) == 0 || iter->children[c] == nullptr) {
iter->children[c] = new TrieNode();
}
iter = iter->children[c];
}
iter->val = val;
}
int sum(string prefix) {
auto iter = root;
for (char c: prefix) {
if (iter->children.count(c) == 0 || iter->children[c] == nullptr) {
return 0;
}
iter = iter->children[c];
}
return sumTail(iter);
}
int sumTail(TrieNode *node) {
if (node == nullptr)
return 0;
int ans = node->val;
for (auto &p : node->children) {
ans += sumTail(p.second);
}
return ans;
}
void free(TrieNode *node) {
if (node == nullptr)
return;
for (auto &p : node->children) {
free(p.second);
}
delete node;
}
virtual ~MapSum() {
free(root);
}
private:
TrieNode *root;
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/
#endif //LEETCODE_677_HPP