forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map-sum-pairs.cpp
79 lines (68 loc) · 1.92 KB
/
map-sum-pairs.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
68
69
70
71
72
73
74
75
76
77
78
79
// Time: O(n), n is the length of key
// Space: O(t), t is the number of nodes in trie
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
}
void insert(string key, int val) {
trie_.Insert(key, val);
}
int sum(string prefix) {
return trie_.GetCount(prefix);
}
private:
struct TrieNode {
bool isString = false;
int count = 0;
int val = 0;
unordered_map<char, TrieNode *> leaves;
void Insert(const string& s, const int val) {
const auto delta = val - GetVal(s);
auto* p = this;
for (const auto& c : s) {
if (p->leaves.find(c) == p->leaves.cend()) {
p->leaves[c] = new TrieNode;
}
p = p->leaves[c];
p->count += delta;
}
p->val = val;
p->isString = true;
}
int GetVal(const string& s) const {
auto* p = this;
for (const auto& c : s) {
if (p->leaves.find(c) == p->leaves.cend()) {
return 0;
}
p = p->leaves.at(c);
}
return p->isString ? p->val : 0;
}
int GetCount(const string& s) const {
auto* p = this;
for (const auto& c : s) {
if (p->leaves.find(c) == p->leaves.cend()) {
return 0;
}
p = p->leaves.at(c);
}
return p->count;
}
~TrieNode() {
for (auto& kv : leaves) {
if (kv.second) {
delete kv.second;
}
}
}
};
TrieNode 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);
*/