题目链接:
力扣https://leetcode-cn.com/problems/map-sum-pairs/
【方法一】直接用python或者java中的字典和字符串的startswith方法
class MapSum:
def __init__(self):
self.map = {}
def insert(self, key: str, val: int) -> None:
self.map[key] = val
def sum(self, prefix: str) -> int:
ans = 0
for k in self.map.keys():
if k.startswith(prefix):
ans += 1
return ans
class MapSum {
public HashMap<String, Integer> hashMap;
public MapSum() {
hashMap = new HashMap<>();
}
public void insert(String key, int val) {
hashMap.put(key, val);
}
public int sum(String prefix) {
int ans = 0;
for(Map.Entry<String, Integer> entry: hashMap.entrySet()){
if(entry.getKey().startsWith(prefix)) ans += entry.getValue();
}
return ans;
}
}
【方法二】字典树
class MapSum {
public int value;
public boolean is_end;
public Map<Character, MapSum> map = new HashMap<>();
/** Initialize your data structure here. */
public MapSum() {
}
public void insert(String key, int val) {
MapSum cur = this;
int n = key.length(), i;
char c;
for(i = 0; i < n; i++){
c = key.charAt(i);
if(cur.map.containsKey(c)) cur = cur.map.get(c);
else{
cur.map.put(c, new MapSum());
cur = cur.map.get(c);
}
}
cur.value = val;
cur.is_end = true;
}
public int dfs(MapSum node){
int ret = 0;
if(node.is_end) ret += node.value;
for(Map.Entry<Character, MapSum> entry: node.map.entrySet()){
ret += dfs(entry.getValue());
}
return ret;
}
public int sum(String prefix) {
int n = prefix.length(), i;
char c;
MapSum cur = this;
for(i = 0; i < n; i++) {
c = prefix.charAt(i);
if(cur.map.containsKey(c)) cur = cur.map.get(c);
else return 0;
}
return dfs(cur);
}
}