题目
实现一个 MapSum 类,支持两个方法,insert 和 sum:
MapSum() 初始化 MapSum 对象
void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。
int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。
示例:
输入:
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["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)
链接:https://leetcode-cn.com/problems/map-sum-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
本题依赖上面文章里面的前缀树的能力,思路和上面基本一致,唯一不同的就是我们需要在前缀树的每个节点对象Node上面维护一个value属性值,用于计算后续的和sum。
public E value;
其具体全部代码如下所示:
package leetcode.editor.cn;
import java.util.Map;
import java.util.TreeMap;
public class P677键值映射 {
public static void main(String[] args) {
MapSum mapSum = new P677键值映射().new MapSum();
mapSum.insert("a", 3);
int ap = mapSum.sum("ap");// return 3 (apple = 3)
System.out.println(ap);
mapSum.insert("b", 2);
ap = mapSum.sum("a");
System.out.println(ap);
}
private class MapSum {
private class Node<E> {
public E value;
// trie 树的子节点
public Map<Character, Node<E>> next;
public Node(E value) {
next = new TreeMap<>();
this.value = value;
}
}
// trie树的根节点
private Node<Integer> root;
// 代表有多少个单词
public MapSum() {
root = new Node<Integer>(0);
}
public void insert(String key, int val) {
insert(root, key, 0, val);
}
private void insert(Node<Integer> node, String word, int index, int val) {
if (index >= word.length()) {
node.value = val;
return;
}
if (node.next.get(word.charAt(index)) != null) {
insert(node.next.get(word.charAt(index)), word, index + 1, val);
} else {
Node newNode = new Node(0);
node.next.put(word.charAt(index), newNode);
insert(newNode, word, index + 1, val);
}
}
public int sum(String prefix) {
Node<Integer> cur = root;
for (int i = 0; i < prefix.length(); i++) {
if (cur.next.get(prefix.charAt(i)) != null) {
cur = cur.next.get(prefix.charAt(i));
} else {
return 0;
}
}
return cur.value + sum(cur);
}
public int sum(Node<Integer> node) {
int result = 0;
for (Node<Integer> n : node.next.values()) {
result = result + n.value + sum(n);
}
return result;
}
}
}