题目:
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
分析:
class TrieNode{
int times;
Map<Character,TrieNode> content;
public TrieNode(){
content=new HashMap<Character,TrieNode>();
}
}
public class MapSum {
//给定单词表,及其出现的次数。
//当出现新的单词时,更新该单词的次数
//分别返回由前缀组成的单词个数
//思路:当遍历到前缀的最后一个字符时,dfs遍历其下面的各次数,因为由该前缀组成的次数便是所求结果
private TrieNode root;
/** Initialize your data structure here. */
public MapSum() {
root=new TrieNode();
}
public void insert(String key, int val) {
//插入
if(key==null||key.length()==0) return ;
TrieNode node=root;
TrieNode tempNode=null;
for(int i=0;i<key.length();i++){
Character c=key.charAt(i);
tempNode=node.content.get(c);
if(tempNode==null){
//新建节点
tempNode=new TrieNode();
//放入node中
node.content.put(c,tempNode);
}
//继续向下
node=tempNode;
}
//已经将单词插入完了,赋值次数
node.times=val;
}
public int sum(String prefix) {
//统计由该单词产生的单词总数
if(prefix==null||prefix.length()==0) return 0;
TrieNode node=root;
TrieNode tempNode=null;
for(int i=0;i<prefix.length();i++){
Character c=prefix.charAt(i);
tempNode=node.content.get(c);
if(tempNode==null){
//说明没有该前缀,直接返回0
return 0;
}
node=tempNode;
}
//已经遍历到最后一个字符了,由该HashMap进行dfs遍历
return dfs(node);
}
public int dfs(TrieNode root){
int count=0;
for(char c:root.content.keySet()){
TrieNode temp=root.content.get(c);
if(temp!=null){
count+=dfs(temp);
}
}
return count+root.times;
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/