java - 编写一个程序来压缩字符串

标签 java string algorithm

问题: 游程编码 (RLE) 是一种简单的“压缩算法”(一种采用数据 block 并减小其大小,从而在更小的空间中生成包含相同信息的 block 的算法)。它的工作原理是用代表整个序列的短“标记”替换相同数据项的重复序列。将 RLE 应用于字符串涉及查找字符串中相同字符重复的序列。每个这样的序列应替换为一个“ token ”,其中包含:

the number of characters in the sequence
the repeating character

如果一个字符不重复,则应将其保留。

例如,考虑以下字符串:

qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT

应用RLE算法后,该字符串被转换为:

q9w5e2rt5y4qw2Er3T

这是我到目前为止所拥有的,我不知道如何计算字符,例如一个字符重复了多少次。有人可以帮忙吗!!!

public class Compress1 {
    public static void main(String[] args){
        System.out.println("Enter a string");
        String input = IO.readString();
        char[] inputChar = input.toCharArray();
        for (int index = 0; index < inputChar.length; index++){
            char current = inputChar[index];

            if (current == (current + 1)){
                int count = 
            }
        }
    }
}

最佳答案

这里不是调试代码,而是一些工作代码:

String input = "qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT";

String previous = input.substring(0, 1);
int count = 1;
for (String c : input.substring(1).split("")) {
    if (previous.equals(c)) {
        count++;
    } else {
        System.out.print((count == 1 ? "" : count) + previous);
        previous = c;
        count = 1;
    }
}
System.out.println((count == 1 ? "" : count) + previous);

输出:

q9w5e2rt5y4qw2Er3T

将其与您自己的进行比较,并按照其逻辑找出错误所在。

关于java - 编写一个程序来压缩字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33492078/

相关文章:

Python字符串 'in'算子实现算法和时间复杂度

c - 如何将多个整数组合成一个字符串并在其间添加符号?

c# - 32x32 矩阵的 BinDCT 实现

algorithm - 仅通过加法计算指数

java - 应用程序在切换 Activity 时退出沉浸模式

java - 想要但没有调用mockito测试

java - 警告 : unknown enum constant Status. 稳定

java - Oracle JDK 7 未安装且 E : Sub-process/usr/bin/dpkg returned an error code (1)

c++ - std string vs char performance,从一开始就删除部分的最佳技术

algorithm - 计算整数中的尾随零最有效的方法是什么?