677 Map Sum Pairs
Input: insert("apple", 3), Output: Null
Input: sum("ap"), Output: 3
Input: insert("app", 2), Output: Null
Input: sum("ap"), Output: 5struct Node {
Node(int val) : end_of_word(false), value(val) {}
unordered_map<char, Node*> children;
bool end_of_word;
int value;
};
class Trie {
public:
Trie() { _root = new Node(0); }
void add(const string& name, int val) {
Node *iter = _root;
for (char c : name) {
if (iter->children.find(c) == iter->children.end()) {
iter->children.insert(make_pair(c, new Node(0)));
}
iter = iter->children.find(c)->second;
}
iter->value = val;
iter->end_of_word = true;
//print_trie(); cout << endl;
}
void print_trie() {
Node *iter = _root;
queue<Node*> q;
q.push(_root);
while (!q.empty()) {
iter = q.front();
q.pop();
for (auto i : iter->children)
cout << i.first << ' ';
cout << endl;
for (auto i : iter->children) {
q.push(i.second);
}
}
}
Node *_root;
};
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
trie = Trie();
}
void insert(string key, int val) {
trie.add(key, val);
}
int sum(string prefix) {
int total_sum = 0;
Node *start = iter_to_prefix(prefix);
if (!start) return 0;
_sum(start, total_sum);
return total_sum;
}
private:
Trie trie;
Node* iter_to_prefix(const string &prefix) {
Node *root = trie._root;
for (char c : prefix) {
if (root->children.find(c) != root->children.end())
root = root->children[c];
else return nullptr;
}
return root;
}
void _sum(Node *cur, int &total_sum) {
if (!cur->children.empty()) {
total_sum += cur->value;
for (auto i : cur->children) {
_sum(i.second, total_sum);
}
}
else total_sum += cur->value;
}
};Last updated