【问题标题】:Java Huffman tree code "Decode" method not workingJava Huffman 树代码“解码”方法不起作用
【发布时间】:2019-12-03 00:45:44
【问题描述】:

我已经研究这种方法有一段时间了,我很确定这是一个简单的解决方案。在我的一生中,我无法弄清楚为什么每当我传递[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] 的布尔数组时我的代码返回strin。出于某种原因,“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;
}

任何帮助将不胜感激。

【问题讨论】:

  • str += leaf.data; 是您添加到 str 的唯一时间。也许leaf.data 总是对或错?
  • @KnowNoTrend leaf.data 是一个字符

标签: java tree huffman-code


【解决方案1】:

问题将是,当您阅读编码中的最后一个条目并将您定向到您的角色时,您立即 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
}

那应该为你抓取最后一个字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多