題目
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
解題思路
把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;
}
}
感想
沒甚麼難度的一道,注意題目條件即可。