代码:
class MapSum {
public:
class dictree{
public:
int val = 0;
vector<dictree*> child;
dictree() {
child.resize(26, nullptr);
}
};
//字典树的根节点
dictree* root = new dictree();
MapSum() {
}
void insert(string key, int val) {
dictree* cur = root;
for (char ch : key)
{
//如果是空的话要先初始化
if (cur->child[ch - 'a'] == nullptr)
{
cur->child[ch - 'a'] = new dictree();
}
cur = cur->child[ch - 'a'];
}
cur->val = val;
}
//寻找以node为根节点的子树的所有值之和
int total(dictree* node)
{
if (node == nullptr) return 0;
int ans = node->val;
for (int i = 0; i < 26; i++)
{
ans += total(node->child[i]);
}
return ans;
}
int sum(string prefix) {
dictree* cur = root;
//先按前缀,沿着字典树找到前缀的最后一个字符所对应的结点
for (char ch : prefix)
{
cur = cur->child[ch - 'a'];
if (cur == nullptr) break; //如果遍历到了空,说明不存在该前缀所对应的键
}
return total(cur);
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/
显而易见的字典树题目,练习一下字典树的写法。