题目链接:https://leetcode-cn.com/problems/map-sum-pairs/comments/
用TreeMap实现类似字典树的功能:
class MapSum {
private class Node{
private int value;
private TreeMap<Character,Node> next;
public Node(int value){
this.value=value;
next=new TreeMap<>();
}
public Node(){
this(0);
}
}
public Node root;
/** Initialize your data structure here. */
public MapSum() {
root=new Node();
}
public void insert(String key, int val) {
Node cur=root;
for(char c: key.toCharArray()){
if(!cur.next.containsKey(c))cur.next.put(c,new Node()) ;
cur=cur.next.get(c);
}
cur.value=val;
}
public int sum(String prefix) {
Node cur=root;
for(char c: prefix.toCharArray()){
if(!cur.next.containsKey(c))return 0;
cur=cur.next.get(c);
}
return sum(cur);
}
private int sum(Node node){
int val=node.value;
for(char c: node.next.keySet())
val+=sum(node.next.get(c));
return val;
}
}