我已经研究这种方法已有一段时间了,我很确定这是一个简单的解决方案。对于我的一生,我无法弄清楚为什么我每次传递strin
的布尔数组时代码都返回[false, true, true, false, false, false, false, false, true, true, false, true, false, true, false, false, true, true, false, false, true, true, true, false, true, true]
的原因。由于某些原因,“ g”永远不会出现在字符串上,而且我似乎无法弄清楚原因。
public String decodeIter(boolean[] coding)
{
String str = "";
Node current = root;
int i = 0;
while(i < coding.length)
{
if(current != null)
{
if(current.left == null && current.right == null)
{
LeafNode leaf = (LeafNode) current;
str += leaf.data;
current = root;
} else {
if(coding[i] == true)
{
current = current.right;
i++;
} else {
current = current.left;
i++;
}
}
}
}
return str;
}
任何帮助将不胜感激。
答案 0 :(得分:0)
问题将是,当您阅读编码中的最后一个条目并将其定向到您的角色时,您立即i ++,这将使循环上的while条件变为假,因此最后一个str + =永远不会被调用因为它的条件从未经过测试。可能会有更清洁的补救方法,但是一种方法是在return str
之前插入以下内容。
if(current!= null && current.left == null && current.right == null)//short circuit prevents dereferencing null pointer
{
LeafNode leaf = (LeafNode) current;
str += leaf.data;
//no need to set current = root, we are leaving anyway
}
那应该为您抓住了最后一个角色。