[英]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.