677. Map Sum Pairs(JAVA)
来源:互联网 发布:ip域名反查询工具 编辑:程序博客网 时间:2024/05/22 13:50
題目
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
解題思路
把map組放進vector裏。每次放入前先檢查string是否相同,若相同則修改其num數值,若沒有相同則push新數據。查找則檢查是否存在子串(不存在返回-1)以及子串是否為前綴(若不為前綴返回值大於0),把所有符合條件的num相加即為返回值。
代碼
import java.util.*;
class MapSum {
Vector<MyMap> map;
/** Initialize your data structure here. */
public MapSum() {
map = new Vector<MyMap>();
}
public void insert(String key, int val) {
int i;
for (i = 0; i < map.size(); i++) {
if (map.get(i).str.equals(key)) {
map.get(i).num = val;
break;
}
}
if (i == map.size()) {
MyMap m = new MyMap(key,val);
map.add(m);
}
}
public int sum(String prefix) {
int sum = 0;
for (int i = 0; i < map.size(); i++) {
if (map.get(i).str.indexOf(prefix) == 0) {
sum += map.get(i).num;
}
}
return sum;
}
}
class MyMap {
public String str;
public int num;
public MyMap(String string, int n) {
str = string;
num = n;
}
}
感想
沒甚麼難度的一道,注意題目條件即可。
- 677. Map Sum Pairs(JAVA)
- 677. Map Sum Pairs
- 677. Map Sum Pairs
- leetcode 677. Map Sum Pairs
- leetcode 677. Map Sum Pairs
- leetcode 677. Map Sum Pairs
- LeetCode 677. Map Sum Pairs
- leetcode 677. Map Sum Pairs
- LWC 50:677. Map Sum Pairs
- LeetCode677. Map Sum Pairs
- Map Sum Pairs问题及解法
- 第14周Map Sum Pairs
- 未完成--Sum of Pairs
- Rust : codewars的Sum of Pairs
- Swap Nodes in Pairs Java
- Swap Nodes in Pairs (Java)
- (Java)-LeetCode-336. Palindrome Pairs
- pairs
- C#个人重构之基本数据设定
- time模块
- zdy拦截器
- 微信分享
- hibernate反转工程
- 677. Map Sum Pairs(JAVA)
- 关于Failed to check the status of the service com.taotao.service.ItemService. No provider available fo
- Linux下安装confluence汉化破解版
- vs2010 瘦身--ipch文件夹和sdf文件配置
- java零基础(二)
- 基于android平台的斗地主AI
- 同构or服务端渲染
- 设置网页中video默认为静音
- 【OpenCV入门教程之二】 一览众山小:OpenCV 2.4.8 or OpenCV 2.4.9组件结构全解析