1 Star 0 Fork 0

徐长贺/Leetcode

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
_677.java 1.42 KB
一键复制 编辑 原始数据 按行查看 历史
stevesun 提交于 2017-09-23 22:17 +08:00 . move 677 out of test directory
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.Map;
/**
* 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
*/
public class _677 {
public static class Solution1 {
public static class MapSum {
Map<String, Integer> 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 sum = 0;
for (String key : map.keySet()) {
if (key.startsWith(prefix)) {
sum += map.get(key);
}
}
return sum;
}
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/isulong/Leetcode.git
git@gitee.com:isulong/Leetcode.git
isulong
Leetcode
Leetcode
master

搜索帮助