我在尝试使用递归压缩字符串时遇到了一些小问题。
例如,考虑以下字符串:
qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT
应用RLE算法后,这个字符串被转换成:
q9w5e2rt5y4qw2Er3T
在压缩后的字符串中,“9w”代表一串9个连续的小写“w”字符。 “5e”代表5个连续的小写“e”字符等。
我已经有了不用递归压缩它的代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Compress {
public static String input(String source) {
StringBuffer coding = new StringBuffer();
for (int i = 0; i < source.length(); i++) {
int runLength = 1;
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
runLength++;
i++;
}
if (runLength>1){
coding.append(runLength);
}
coding.append(source.charAt(i));
}
return coding.toString();
}
public static void main(String[] args) {
IO.outputStringAnswer("Enter a string");
String str = IO.readString();
String result = "";
result=input(str); //function(variable)
IO.outputStringAnswer(result);
}
}
但我不确定是否可以将其转换为递归版本。
最佳答案
这很可能是您正在寻找的:
public static String compress(String source) {
if (source.length() <= 1) return source;
int runLength = 1;
while (runLength < source.length() && source.charAt(0) == source.charAt(runLength)) {
runLength++;
}
String lengthString = runLength > 1 ? String.valueOf(runLength) : "";
return lengthString + source.substring(0,1) + compress(source.substring(runLength));
}
我假设您的源字符串不包含任何数字。如您所见,该函数在最后一行使用源字符串的其余部分递归调用自身。
关于java - 如何使用递归压缩字符串? (RLE算法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20201279/