算法题:RLE压缩算法(游程编码)的Java实现

RLE全称run-length encoding,又称为游程编码,或者长度编码变动长度编码法run coding)。例如,我们输入字符串"qwweeerrrrttttt",经过压缩之后的输出结果应该为"1q2w3e4r5t"。
以下分别使用Java递归和尾递归的方式来实现。

  • 递归方式实现
    public static String RLECompress(String source) {
        if (source.length() <= 1) return source;

        int runLength = 1;
        while (runLength < source.length() && source.charAt(0) == source.charAt(runLength)) {
            runLength++;
        }

        return runLength + source.substring(0, 1) + RLECompress(source.substring(runLength));
    }
  • 尾递归方式实现
    public static String RLECompressWithTail(String source, String result) {
        if (source.length() <= 0) return result;

        int runLength = 1;
        while (runLength < source.length() && source.charAt(0) == source.charAt(runLength)) {
            runLength++;
        }
        result += runLength + source.substring(0, 1);
        return  RLECompressWithTail(source.substring(runLength), result);
    }

参考
//http://www.6tie.net/p/908340.html

你可能感兴趣的:(#,面试经验,Java,#,算法)