[英]Recursive Java RLE Decompression Method [stackoverflow error]
我正在尝试用Java编写一个程序,该程序使用递归对压缩的RLE语句进行解压缩,但是我不断收到堆栈溢出错误,我不知道为什么。
到目前为止,这是我写的内容:
public class StringRec
{
public static void main (String args[]){
System.out.println(decompress("wed4d"));
}
//Version 0.1
public static String decompress(String compressedText)
{ String cText = compressedText;
StringBuffer newString = new StringBuffer();
int i = 0;
if (cText==""){return newString.toString();}
if(!cText.isEmpty()){
if(Character.isLetter(cText.charAt(i))){
newString.append(cText.charAt(i));
cText = cText.substring(1,cText.length());
return decompress(cText);
//remove first letter, return new modified string with removed first letter to decompress.
}
if(Character.isDigit(cText.charAt(i))){
int c = cText.charAt(i)-'0';
if (c==0){
cText = cText.substring(2,cText.length());}
return decompress(cText);
//delete c and the letter after it and send new modified string to decompress.
}
}else {
newString.append(cText.charAt(i+1));
int c = cText.charAt(i);
c--;
String num = ""+c;
cText = cText.replaceFirst(num, Character.toString(cText.charAt(i)));
return decompress(cText);
//appends character after number to newString, decrements the number and returns
//the new modified string to decompress with the first number decremented by one
}
return newString.toString();
}
}
递归的基本情况是一个空字符串,如果该字符串以一个字母开头,则该字母仅添加一次到字符串缓冲区newString中,并且原始字符串的第一个字母从字符串序列中删除,并将新字符串传递给解压缩; 如果它以零开始,则删除字符串的前两个字符,并将新字符串传递给解压缩。
如果它是一个大于0 [else]的数字,那么它前面的字母将添加到字符串缓冲区newString中,并且该数字将递减,并替换字符串开头的数字,然后将新字符串[以原始的第一个字符数传递给-1]解压缩。
我相信无限递归的发生是因为:
int c = cText.charAt(i);
c--;
String num = ""+c;
cText = cText.replaceFirst(num, Character.toString(cText.charAt(i)));
如果字符为1
,则c
为65,即字符'1'
的ASCII值。 然后将num
设置为字符串"64"
,如果您的字符串中没有"64"
,则该方法将不断重复使用同一字符串进行调用。 将c
声明为char
应该可以解决该问题。 另外,请注意replaceFirst
表示要搜索与第一个参数匹配的模式,然后将其替换为第二个参数。 您可能会倒退。 另外,请参阅上面有关newString
评论。
编辑:要回答您的评论:使用StringBuffer是可以的。 您不能做的是让每个decompress
创建一个new StringBuffer
,因为每次调用decompress
都会创建一个新的StringBuffer
,这不是您想要的。 如果decompress
使用StringBuffer newString
参数,并且每次decompress
调用自身时都会将newString
作为参数传递,则每个decompress
调用都将指向同一 StringBuffer
,因为它是对对象的引用。
我想您暗示的另一种方法是,由于decompress
返回一个String
,因此每次decompress
调用其自身时,都可以使用函数结果(现在您的代码只是将其丢弃),并且可能将该函数结果与其他结果连接在一起并返回新字符串。 我认为您可以使这种方法可行,但我尚未对其进行深入研究。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.