老师,我自己试了一下是成功的,但是在leetcode是失败,我想问一下是我的代码有哪里错了吗
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
MapSum sum = new MapSum();
sum.insert("apple", 5);
sum.insert("app", 3);
System.out.println(sum.sum("a"));
}
}
class MapSum {
private class Node {
public boolean isWord;
public int value;
public TreeMap<Character, Node> next;
public Node(boolean isWord, int value) {
this.isWord = isWord;
this.value = value;
next = new TreeMap<>();
}
public Node(boolean isWord) {
this(isWord, 0);
}
public Node() {
this(false, 0);
}
public Node set(int value) {
this.value = value;
return this;
}
}
private Node root;
/** Initialize your data structure here. */
public MapSum() {
root = new Node();
}
public void insert(String key, int val) {
Node cur = root;
for(int i = 0; i < key.length(); i++) {
char c = key.charAt(i);
if(cur.next.get(c) == null)
cur.next.put(c, new Node(false, val));
else
cur.next.put(c, cur.next.get(c).set(cur.next.get(c).value + val));
cur = cur.next.get(c);
}
if(!cur.isWord) {
cur.isWord = true;
}
}
public int sum(String prefix) {
Node cur = root;
for(int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if(cur.next.get(c) == null)
return 0;
cur = cur.next.get(c);
}
return cur.value;
}
}