leetcode 677. 键值映射

实现一个 MapSum 类,支持两个方法,insert 和 sum:

MapSum() 初始化 MapSum 对象
void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。
int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。

示例:

输入:

["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");           // return 3 (apple = 3)
mapSum.insert("app", 2);    
mapSum.sum("ap");           // return 5 (apple + app = 3 + 2 = 5)

提示:

1 <= key.length, prefix.length <= 50
key 和 prefix 仅由小写英文字母组成
1 <= val <= 1000
最多调用 50 次 insert 和 sum

AC代码

#include "bits/stdc++.h"
using namespace std;

const int TRIE_NODE_SIZE = 26;

// 字典树节点
struct TrieNode {
    TrieNode* next[TRIE_NODE_SIZE];
    bool isEnd;
    int times; // 记录值
    TrieNode()
    {
        for (int i = 0; i < TRIE_NODE_SIZE; ++i) {
            next[i] = nullptr;
            isEnd = false;
            times = 0; // value范围[1, 1000]
        }
    }
};

// 字典树
class Trie {
public:
    Trie() {
        root = new TrieNode();
    }
    
    void insert(string word, int value) {
        TrieNode* node = root;
        for (const auto& ch : word) {
            if (node->next[ch - 'a'] == nullptr) {
                node->next[ch - 'a'] = new TrieNode();
            }
            node = node->next[ch - 'a'];
        }
        node->isEnd = true;
        node->times = value; // 用“=”不用“+=”
    }

    // 递归查找node后续节点值之和
    void dfs(TrieNode* node, int& sum) {
        if (node->isEnd) {
            sum += node->times;
        }
        for (int i = 0; i < TRIE_NODE_SIZE; ++i) {
            if (node->next[i] != nullptr) {
                dfs(node->next[i], sum); 
            }
        }
        return;
    }

    // 查找前缀prefix出现的次数
    int getSum(string prefix) {
        int sum = 0;
        TrieNode* node = root;
        for (const auto& ch : prefix) {
            if (node->next[ch - 'a'] != nullptr) {
                node = node->next[ch - 'a'];
            } else {
                return 0;
            }
        }
        // 此时node已经到达prefix最后一个字母
        dfs(node, sum);
        return sum;
    }


public:
    TrieNode* root; // 根节点
};

// 键值对
class MapSum {
public:
    MapSum() {
        trie = new Trie();
    }
    
    void insert(string key, int val) {
        trie->insert(key, val);
    }
    
    int sum(string prefix) {
        return trie->getSum(prefix);
    }

public:
    Trie* trie;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值