[leetcode]677. Map Sum Pairs

[leetcode]677. Map Sum Pairs


Analysis

ummmmm~—— [ummmm]

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.
用hash table实现就可以~

Implement

class MapSum {
public:
    map<string, int> mymap;
    /** Initialize your data structure here. */
    MapSum() {

    }

    void insert(string key, int val) {
        mymap[key] = val;
    }

    int sum(string prefix) {
        int res = 0;
        int len = prefix.size();
        map<string, int>::iterator it;
        for(it=mymap.begin(); it!=mymap.end(); it++){
            string tmp = it->first;
            if(prefix == tmp.substr(0, len))
                res += it->second;
        }
        return res;
    }
};

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum obj = new MapSum();
 * obj.insert(key,val);
 * int param_2 = obj.sum(prefix);
 */

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/82502757
今日推荐