如何使用递归压缩字符串?(RLE算法)

ACh*_*hoi 4 java regex compression algorithm recursion

我在尝试使用递归压缩字符串时遇到了一些麻烦。

例如,考虑以下字符串:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我不确定这是否能够变成它的递归版本。

lex*_*x82 5

这很可能就是您正在寻找的:

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));
}
Run Code Online (Sandbox Code Playgroud)

我假设您的源字符串不包含任何数字。正如您所看到的,该函数在最后一行中使用源字符串的其余部分递归地调用自身。