1、题目描述
2、解题思路
典型的字典树题目,使用其可以快速的匹配前缀操作。每个节点带一个值,如果是单词路径上的节点,权值直接赋值为0即可。
代码
class Trie {
struct TrieNode {
int val;
TrieNode *child[26];
TrieNode(int x) {
val = x;
for (int i = 0; i < 26; i++) {
child[i] = nullptr;
}
}
};
TrieNode *root;
public:
Trie () {
root = new TrieNode(-1);
}
void insert(string& s, int val) {
auto p = root;
for (char c : s) {
if (!p->child[c - 'a']) {
p->child[c - 'a'] = new TrieNode(0);
}
p = p->child[c - 'a'];
}
p->val = val;
}
int presum(string& s) {
int sum = 0;
auto p = root;
for (char c : s) {
if (!p->child[c - 'a']) return 0;
p = p->child[c - 'a'];
}
queue<TrieNode*> q;
q.push(p);
while (!q.empty()) {
auto cur = q.front();
q.pop();
sum += cur->val;
for (int i = 0; i < 26; i++) {
if (cur->child[i]) {
q.push(cur->child[i]);
}
}
}
return sum;
}
};
class MapSum {
public:
/** Initialize your data structure here. */
Trie *t;
MapSum() {
t = new Trie();
}
void insert(string key, int val) {
t->insert(key, val);
}
int sum(string prefix) {
return t->presum(prefix);
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/