leetcode677+Map sum使用map就行,加上一个starts_with函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013554860/article/details/83312203

https://leetcode.com/problems/map-sum-pairs/description/

class MapSum {
public:
    map<string, int> pairs;
    /** Initialize your data structure here. */
    bool starts_with(string s, string t)
    {
        return s.substr(0, t.size())==t;
    }
    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;
    }
};

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/83312203