【发布时间】:2021-12-25 05:54:58
【问题描述】:
我来寻求您的帮助,我在学校做了一个项目,要求我们创建一个霍夫曼程序,到目前为止一切都很好......我的问题是我负责解码文本的递归函数似乎很漂亮不好,因为它在〜3500递归后给了我一个stackOverflow,以便构建一个长文本。我尝试了很多东西,但我想不出一个想法来解决似乎是递归次数的主要问题。我将在这里向您展示我的主要功能。
这是编码之一:
public static String codeText(String textString, HashMap<String, String> tableCode) {
if(textCode.isEmpty()) {
return textCode;
}
String encode = ""; // Final code
String[] lineSplit = texteString.split(""); // I use a string so I need to split it
for (String element : lineSplit) {
if (tableCode.containsKey(element)) {
encode += tableCode.get(element.toLowerCase());//I use lower case cause I don't know how to detect the capitals
} else {
encode += tableCode.get("?"); // If the char isn't in our huffman tree
}
}
return encode;
}
现在的主要问题,我真的不知道如何让它变得不同
// Launcher to build our arrayOfString
public static String decodeText(Node huffman, Node huffmanFull, String textCode) {
String textDecode = ""; //Final text
ArrayList<String> arrayOfCode = new ArrayList<>(); //Code split into an array
String[] textSplit = textCode.split("");
for (String element : textSplit) {
arrayOfCode.add(element);
}
return decodeText2(huffman, huffmanFull, arrayOfCode, textDecode);
}
public static String decodeText2(Node huffman, Node huffmanFull, ArrayList<String> arrayOfCode, Node textDecode) {
if (huffman.vide()) {
return textDecode;
}
if (arrayOfCode.size() == 0) {
textDecode += huffman.getData();// We add the last char
return textDecode;
}
if (huffman.getData() == null) { // We travel arround the tree in order to find the associate char
if (arrayOfCode.get(0).equals("0")) { // if the code is 0 go left child
arrayOfCode.remove(0); //we remove the actual index
return decodeText2(huffman.left(), huffmanFull, arrayOfCode, textDecode);
} else if (arrayOfCode.get(0).equals("1")) {// 1 we go right
arrayOfCode.remove(0);
return decodeText2(huffman.right(), huffmanFull, arrayOfCode, textDecode);
}
} else {
the char from the code has been found
textDecode += huffman.getData() ; // we add it to the string
return decodeText2(huffman = huffmanFull, huffmanFull, arrayOfCode, textDecode); // We reset the huffman tree with the full one
}
return textDecode;
}
我希望它足够清楚,感谢您的指导。
【问题讨论】:
-
给定一个足够大的问题,所有的递归(在 Java 中)最终都会以
StackOverflowError结束。这就是野兽的本性。如果我们想完全避免这个问题,我们将不得不将代码重写为迭代,而不是递归。 -
我希望可以,使用递归很痛苦,但这是我们老师想要的。而且我已经用尽了我所有的想法,因为现在的代码大约是 14000 字符并且溢出方式太快了
标签: java recursion huffman-code