我在尝试使用递归压缩字符串时遇到了一些麻烦。
例如,考虑以下字符串:
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 = ""; …Run Code Online (Sandbox Code Playgroud)