【发布时间】:2015-05-02 01:57:33
【问题描述】:
我的算法构造一个单词并在 TST 中查找与该单词关联的值。
private Node get(Node x, String key, int index) {
if (key.isEmpty()) {
return root;
}
if (x == null) {
return null;
}
char c = key.charAt(index);
if (c < x.val) {
return get(x.left, key, index);
} else if (c > x.val) {
return get(x.right, key, index);
} else if (index < key.length() - 1) {
return get(x.mid, key, index + 1);
} else {
return x;
}
}
每个节点都是这样构造的:
private class Node {
private char val;
private Node left, mid, right;
private Double selfWeight;
private double maxWeight;
/**
* Node constructor.
*/
private Node(char c) {
val = c;
maxWeight = 0.0;
selfWeight = null;
}
}
构建时设置单词的maxWeight,是TST标准构建的修改版:
private Node put(Node x, String key, Double weight, int index) {
char c = key.charAt(index);
if (x == null) {
x = new Node();
x.val = c;
}
if (c < x.val) {
x.left = put(x.left, key, weight, index);
} else if (c > x.val) {
x.right = put(x.right, key, weight, index);
} else if (index < key.length() - 1) {
x.mid = put(x.mid, key, weight, index + 1);
} else {
x.selfWeight = weight;
}
if (weight > x.maxWeight) {
x.maxWeight = weight;
}
return x;
}
运行我的算法时,如果我插入,例如权重为 20 的“你好”,我在 get("hello" + '\u0000'); 上进行搜索,该方法将返回 null,就好像我调用 get("hello") 该方法将返回 20。这是为什么?
我的逻辑是添加“null”字符不会更改字符串,打印出"hello" + '\u0000' 可以确认这一点。发生了什么?
【问题讨论】: