其他分享
首页 > 其他分享> > LeetCode 677. 键值映射

LeetCode 677. 键值映射

作者:互联网

题目链接

思路:初始化为HashMap,对每个键值对进行存储,搜索给定的前缀时,遍历HashMap中的key,如果包含前缀,就对其value进行相加。

代码:

class MapSum {
    HashMap<String,Integer> map;
    public MapSum() {
        map = new HashMap<>();
    }
    
    public void insert(String key, int val) {
        map.put(key,val);
    }
    
    public int sum(String prefix) {
        int s=0;
        for(String key:map.keySet()){
            if(key.indexOf(prefix)==0) s+=map.get(key);
        }
        return s;
    }
}

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

标签:map,HashMap,int,677,prefix,键值,MapSum,key,LeetCode
来源: https://blog.csdn.net/CJason_/article/details/121314220