-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path677.cpp
46 lines (42 loc) · 1 KB
/
677.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
// hashmap+trie.cpp
class MapSum {
struct trie_node {
trie_node *children[26];
int val;
trie_node() { memset(this, 0, sizeof(trie_node)); }
} root;
unordered_map<string, int> words;
public:
/** Initialize your data structure here. */
MapSum() {}
void insert(string key, int val) {
auto word = words.find(key);
if (word != words.end())
val = val - word->second;
words[key] = val;
trie_node *p = &root;
for (char ch : key) {
if (!p->children[ch - 'a'])
p->children[ch - 'a'] = new trie_node();
p = p->children[ch - 'a'];
p->val += val;
}
}
int sum(string prefix) {
trie_node *p = &root, *child;
int i;
for (i = 0; i < prefix.size(); ++i) {
child = p->children[prefix[i] - 'a'];
if (!child)
return 0;
p = child;
}
return p->val;
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/