力扣-键值映射

这篇博客介绍了如何使用字典树(Trie)数据结构实现键值映射的功能。代码中展示了MapSum类的设计,包括插入键值对和根据前缀查找所有键对应值的总和。通过实例操作,展示了字典树在字符串搜索和前缀匹配上的高效性。
摘要由CSDN通过智能技术生成

题目链接:677. 键值映射 - 力扣(LeetCode)

代码:

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);
 */

 显而易见的字典树题目,练习一下字典树的写法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值