实现一个 MapSum
类,支持两个方法,insert
和 sum
:
MapSum()
初始化MapSum
对象void insert(String key, int val)
插入key-val
键值对,字符串表示键key
,整数表示值val
。如果键key
已经存在,那么原来的键值对将被替代成新的键值对。int sum(string prefix)
返回所有以该前缀prefix
开头的键key
的值的总和。
示例:
输入:
inputs = ["MapSum", "insert", "sum", "insert", "sum"]
inputs = [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
输出:
[null, null, 3, null, 5]
解释:
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);
mapSum.sum("ap"); // return 3 (apple = 3)
mapSum.insert("app", 2);
mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5)
提示:
1 <= key.length, prefix.length <= 50
key
和prefix
仅由小写英文字母组成1 <= val <= 1000
- 最多调用
50
次insert
和sum
//leetcode submit region begin(Prohibit modification and deletion)
class MapSum {
class Trie {
private Trie[] leaves;
private int sum;
Map<String, Integer> valMap;
public Trie() {
this.leaves = new Trie[26];
this.sum = 0;
this.valMap = new HashMap<>();
}
public void addWord(String word, int val) {
if (word == null) {
return;
}
int value = val;
if (valMap.containsKey(word)) {
value -= valMap.get(word);
}
valMap.put(word, val);
Trie trie = this;
for (int i = 0; i < word.length(); i++) {
if (trie.leaves[word.charAt(i) - 'a'] == null) {
trie.leaves[word.charAt(i) - 'a'] = new Trie();
}
trie = trie.leaves[word.charAt(i) - 'a'];
trie.sum += value;
}
}
}
private Trie root;
/** Initialize your data structure here. */
public MapSum() {
this.root = new Trie();
}
public void insert(String key, int val) {
this.root.addWord(key, val);
}
public int sum(String prefix) {
if (prefix == null) {
return 0;
}
Trie trie = root;
for (int i = 0; i < prefix.length(); i++) {
if (trie.leaves[prefix.charAt(i) - 'a'] == null) {
return 0;
}
trie = trie.leaves[prefix.charAt(i) - 'a'];
}
return trie.sum;
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/
//leetcode submit region end(Prohibit modification and deletion)