我正在尝试解压看起来如下的字符串:
输入:4(ab)
输出:abababab
输入:11ab
输出:aaaaaaaaaaab
输入:2(3b3(ab))
输出:bbbabababbbbababab
上述示例都可以使用以下递归方法正确地输出,但是当我输入像这样的内容时会出现问题:
输入:4(ab)a
期望输出:ababababa
输入:2(3b3(ab))a
期望输出:bbbabababbbbabababa
我意识到问题出现在"return repeated"语句中。在当前状态下,递归将继续进行,直到达到输入字符串的末尾,即使是在结束括号之后。基本上,如果达到结束括号,我不知道如何让它停止并继续处理剩余部分。在2(3b3(ab))a中,它应该返回2*(3b3(ab))+a,但现在它返回2*(3b3(ab))a。非常感谢任何帮助,因为我无法理解它。
public static String decompress(String compressedText) throws Exception
{
//BASE CASE
if(compressedText.length() == 1)
{
if(compressedText.charAt(0) == ')')
{
System.out.println("1: " + compressedText);
return "";
}
else
{
System.out.println("2: " + compressedText);
return compressedText;
}
}
//END BASECASE
if(compressedText.charAt(0) == '(')
{
System.out.println("3: " + compressedText);
return decompress(compressedText.substring(1));
}
//IF DOUBLE DIGIT
if(Character.isDigit(compressedText.charAt(0)) == true && Character.isDigit(compressedText.charAt(1)) == true)
{
if(compressedText.charAt(3) != '(')
{
System.out.println("4: " + compressedText);
int i = Integer.parseInt(compressedText.substring(0,2));
String repeated = new String(new char[i]).replace("\0", compressedText.substring(2,3));
return repeated + decompress(compressedText.substring(3));
}
else
{
System.out.println("5: " + compressedText);
int i = Integer.parseInt(compressedText.substring(0,2));
String repeated = new String(new char[i]).replace("\0", decompress(compressedText.substring(2)));
return repeated;
}
}
//END DOUBLE DIGIT
//IF SINGLE DIGIT
if (Character.isDigit(compressedText.charAt(0)) == true)
{
if(compressedText.charAt(1) !='(')
{
System.out.println("6: " + compressedText);
int i = Integer.parseInt(compressedText.substring(0,1));
String repeated = new String(new char[i]).replace("\0", compressedText.substring(1,2));
return repeated + decompress(compressedText.substring(2));
}
else
{
System.out.println("7: " + compressedText);
int i = Integer.parseInt(compressedText.substring(0,1));
String repeated = new String(new char[i]).replace("\0", decompress(compressedText.substring(1)));
return repeated;
}
}
//END SINGLE DIGIT
//IF RIGHT PARENTHESIS
if (compressedText.charAt(0) == ')')
{
if (compressedText.charAt(1) != ')')
{
System.out.println("8: " + compressedText);
return "";
}
else
{
System.out.println("9: " + compressedText);
return decompress(compressedText.substring(1));
}
}
//END
System.out.println("10: " + compressedText);
return compressedText.charAt(0)+decompress(compressedText.substring(1));
}
2(3b3(ab))a
的预期输出是bbbabababbbbabababa
。 - Eric Duminil