677. Map Sum Pairs

网友投稿 241 2022-09-17

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: NullInput: sum("ap"), Output: 3Input: insert("app", 2), Output: NullInput: sum("ap"), Output: 5

思路: For each key in the map, if that key starts with the given prefix, then add it to the answer.

class MapSum { HashMap map; /** Initialize your data structure here. */ public MapSum() { map = new HashMap<>(); } public void insert(String key, int val) { map.put(key, val); } public int sum(String prefix) { int ans = 0; for (String key: map.keySet()) { if (key.startsWith(prefix)) { ans += map.get(key); } } return ans; }}/** * Your MapSum object will be instantiated and called as such: * MapSum obj = new MapSum(); * obj.insert(key,val); * int param_2 = obj.sum(prefix); */

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:休克文案:这 7 句年货文案,很暖!
下一篇:713. Subarray Product Less Than K
相关文章

 发表评论

暂时没有评论,来抢沙发吧~