LeetCode每日一题(Map Sum Pairs)

Implement the MapSum class:

MapSum() Initializes the MapSum object.
void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
int sum(string prefix) Returns the sum of all the pairs’ value whose key starts with the prefix.

Example 1:

Input
[“MapSum”, “insert”, “sum”, “insert”, “sum”]
[[], [“apple”, 3], [“ap”], [“app”, 2], [“ap”]]
Output
[null, null, 3, null, 5]

Explanation

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)

Constraints:

1 <= key.length, prefix.length <= 50
key and prefix consist of only lowercase English letters.
1 <= val <= 1000
At most 50 calls will be made to insert and sum.


用Trie来解决,但是我们不一定非要用树来实现,两个HashMap,一个用来存路径节点,一个用来存叶子节点。这样可以更轻松的解决更新叶子节点值的问题。


use std::collections::HashMap;

struct MapSum {
    m: HashMap<String, i32>,
    keys: HashMap<String, i32>,
}

impl MapSum {
    fn new() -> Self {
        Self {
            m: HashMap::new(),
            keys: HashMap::new(),
        }
    }

    fn insert(&mut self, key: String, val: i32) {
        let mut s = String::new();
        if self.keys.contains_key(&key) {
            let ori = *self.keys.get(&key).unwrap();
            for c in key.chars() {
                s.push(c);
                *self.m.entry(s.clone()).or_insert(0) += val - ori;
            }
            self.keys.insert(key, val);
        } else {
            for c in key.chars() {
                s.push(c);
                *self.m.entry(s.clone()).or_insert(0) += val;
            }
            self.keys.insert(key, val);
        }
    }

    fn sum(&self, prefix: String) -> i32 {
        *self.m.get(&prefix).unwrap_or(&0)
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值