677. Map Sum Pairs

Implement a MapSum class with insert, and sum methods.

For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.

For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix.

Example 1:

Input: insert("apple", 3), Output: Null
Input: sum("ap"), Output: 3
Input: insert("app", 2), Output: Null
Input: sum("ap"), Output: 5

实现MapSum 数据结构,其中包含两个方法insert和sum。insert是记录一个字符串-整数对。sum是求所有键值的前缀为prefix的对的数字和。使用unordered_map记录键值对。实现starts_with函数来判断是否是前缀。则insert和sum方法很容易就实现了。


代码:

class MapSum {
public:
    /** Initialize your data structure here. */
    MapSum() {
        
    }
    
    void insert(string key, int val) {
        pairs[key] = val;
    }
    
    int sum(string prefix) {
        int res = 0;
        for(auto p:pairs) {
            if(starts_with(p.first, prefix)) {
                res += p.second;
            }
        }
        return res;
    }

private:
    unordered_map<string, int> pairs;

    bool starts_with(string s, string t) {
        return s.substr(0, t.size()) == t;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值