【数据结构-Trie树】力扣677. 键值映射

设计一个 map ,满足以下几点:

字符串表示键,整数表示值

返回具有前缀等于给定字符串的键的值的总和

实现一个 MapSum 类:

MapSum() 初始化 MapSum 对象

void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对 key-value 将被替代成新的键值对。

int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。

示例 1:

输入:

"MapSum", "insert", "sum", "insert", "sum"

\[\], \["apple", 3\], \["ap"\], \["app", 2\], \["ap"\]

输出:

null, null, 3, null, 5

解释:

MapSum mapSum = new MapSum();

mapSum.insert("apple", 3);

mapSum.sum("ap"); // 返回 3 (apple = 3)

mapSum.insert("app", 2);

mapSum.sum("ap"); // 返回 5 (apple + app = 3 + 2 = 5)

提示:

1 <= key.length, prefix.length <= 50

key 和 prefix 仅由小写英文字母组成

1 <= val <= 1000

最多调用 50 次 insert 和 sum

字典树

cpp 复制代码
class MapSum {
private:
    struct trie{
        vector<trie*> children;
        int v;
        trie():children(26, nullptr), v(-1){};
    };
    trie* root;
public:
    MapSum(){
        root = new trie();
    }
    
    void insert(string key, int val) {
        trie* node = root;
        for(char ch : key){
            ch -= 'a';
            if(node->children[ch] == nullptr){
                node->children[ch] = new trie();
            }
            node = node->children[ch];
        }
        node->v = val;
    }
    
    int sum(string prefix) {
        trie* node = root;
        for(char ch : prefix){
            ch -= 'a';
            if(node->children[ch] == nullptr){
                return 0;
            }
            node = node->children[ch];
        }

        return searchV(node);
    }

    int searchV(trie* node){
        int search_sum = 0;
        if(node->v != -1){
            search_sum += node->v;
        }
        for(int i = 0; i < 26; i++){
            if(node->children[i] != nullptr){
                search_sum += searchV(node->children[i]);
            }
        }
        return search_sum;
    }
};

首先我们在insert的时候就在构建一个字典树,当一个单词在字典树插入完毕后,会更新最后一个字符所在节点的值。

当我们调用sum的时候,会先从字典树的根节点向下寻找到prefix的最后一个字符的节点,如果prefix在字典树中无法查找到,那么就直接返回0。查找到prefix最后一个字符的节点后,我们要开始计算以该节点开始,遍历所有的子节点,当v不为-1的时候,就说明该节点的字符是某个单词的结尾,那么我们就将该单词映射的值v加到search_sum中。由于我们是不断搜索字典树来查找所有的字符组合,所以我们在累加search_sum的时候就采用递归的方式。最后searchV储存的就是所有以该prefix为前缀的单词的映射的累加值。

相关推荐
海清河晏11111 分钟前
数据结构 | 单循环链表
数据结构·算法·链表
wuweijianlove4 小时前
算法性能的渐近与非渐近行为对比的技术4
算法
_dindong4 小时前
cf1091div2 C.Grid Covering(数论)
c++·算法
AI成长日志4 小时前
【Agentic RL】1.1 什么是Agentic RL:从传统RL到智能体学习
人工智能·学习·算法
黎阳之光5 小时前
黎阳之光:视频孪生领跑者,铸就中国数字科技全球竞争力
大数据·人工智能·算法·安全·数字孪生
skywalker_115 小时前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia5 小时前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
wfbcg5 小时前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒6 小时前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode
计算机安禾6 小时前
【数据结构与算法】第36篇:排序大总结:稳定性、时间复杂度与适用场景
c语言·数据结构·c++·算法·链表·线性回归·visual studio