题目
题源
代码
码源
class MapSum {
private class Node {
Node[] child = new Node[26];
int val;
}
private Node root;
public MapSum() {
root = new Node();
}
public void insert(String key, int val) {
insert(key, root, val);
}
private void insert(String key, Node node, int val) {
if (node == null) return;
if (key.length() == 0) {
node.val = val;
return;
}
int index = index4Char(key.charAt(0));
if (node.child[index] == null) {
node.child[index] = new Node();
}
insert(key.substring(1), node.child[index], val);
}
public int sum(String prefix) {
return sum(prefix, root);
}
private int sum(String prefix, Node node) {
if (node == null) return 0;
if (prefix.length() != 0) {
int index = index4Char(prefix.charAt(0));
return sum(prefix.substring(1), node.child[index]);
}
int sum = node.val;
for (Node child : node.child) {
sum += sum(prefix, child);
}
return sum;
}
private int index4Char(char c) {
return c - 'a';
}
}