在Java中压缩字符串

在Java中压缩字符串,java,Java,不知道为什么我的代码不起作用。如果我输入qwwweeeerrtyyyyyqqqqweerttt,当我应该得到q9w5e2ry5y4qe2et3t时,我得到了qw9w5e2rt5y4qw2er3t 游程长度编码(RLE)是一种简单的“压缩算法”(一种采用数据块并减小其大小的算法,以更少的空间生成包含相同信息的块)。它的工作原理是用表示整个序列的短“标记”替换相同数据项的重复序列。对字符串应用RLE需要在字符串中查找重复相同字符的序列。每个这样的序列应替换为“令牌”,包括: 序列中的字符数 重复字符

不知道为什么我的代码不起作用。如果我输入
qwwweeeerrtyyyyyqqqqweerttt
,当我应该得到
q9w5e2ry5y4qe2et3t
时,我得到了
qw9w5e2rt5y4qw2er3t

游程长度编码(RLE)是一种简单的“压缩算法”(一种采用数据块并减小其大小的算法,以更少的空间生成包含相同信息的块)。它的工作原理是用表示整个序列的短“标记”替换相同数据项的重复序列。对字符串应用RLE需要在字符串中查找重复相同字符的序列。每个这样的序列应替换为“令牌”,包括:

序列中的字符数 重复字符 如果某个字符不重复,则应将其单独保留

例如,考虑以下字符串:

qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT
应用RLE算法后,此字符串将转换为:

q9w5e2rt5y4qw2Er3T
在压缩字符串中,
“9w”
表示由9个连续的小写
“w”
字符组成的序列<代码>“5e”表示5个连续的小写
“e”
字符等

编写一个程序,将字符串作为输入,使用RLE对其进行压缩,然后输出压缩后的字符串。大小写事项-大写和小写字符应视为不同。您可以假定输入字符串中没有数字字符。输入没有其他限制-它可能包含空格或标点符号。无需将非字母字符与字母区别对待

    public class Compress{
    public static void main(String[] args){
        System.out.println("Enter a string: ");
        String str = IO.readString();
        int count = 0;
        String result = "";

        for (int i=1; i<=str.length(); i++) {
            char a = str.charAt(i-1);
            count = 1;

            if (i-2 >= 0) {
            while (i<=str.length() && str.charAt(i-1) == str.charAt(i-2)) {
                count++;
                i++;
            }
            }
            if (count==1) {
                result = result.concat(Character.toString(a));
            }
            else {
                result = result.concat(Integer.toString(count).concat(Character.toString(a)));
            }
        }
        IO.outputStringAnswer(result);
    }
}
公共类压缩{
公共静态void main(字符串[]args){
System.out.println(“输入字符串:”);
String str=IO.readString();
整数计数=0;
字符串结果=”;
对于(int i=1;i=0){

而(i我将从零开始,并展望:

public static void main(String[] args){
    System.out.println("Enter a string: ");
    String str = IO.readString();
    int count = 0;
    String result = "";

    for (int i=0; i < str.length(); i++) {
        char a = str.charAt(i);
        count = 1;

        while (i + 1 < str.length() && str.charAt(i) == str.charAt(i+1)) {
            count++;
            i++;
        }

        if (count == 1) {
            result = result.concat(Character.toString(a));
        } else {
            result = result.concat(Integer.toString(count).concat(Character.toString(a)));
        }
    }

    IO.outputStringAnswer(result);
}

您不应该从位置
0
而不是
1
开始吗?Java是零indexed@MadProgrammer,否。我收到以下错误消息:线程“main”中出现异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1您的
while
中的条件有问题。但是,我认为您应该尝试自己调试它,而不是我们给您答案。如果您没有使用带调试器的IDE,请尝试添加一些
System.out.println
以查看需要哪些字符你试过调试你的代码吗?我仍然认为你的逻辑是倒退的,但这可能与我如何处理这个问题有关。。。
qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT => q9w5e2rt5y4qw2Er3T
qqwwwwwwwweeeeerrtyyyyyqqqqwEErTTT => 2q8w5e2rt5y4qw2Er3T
qqwwwwwwwweeeeerrtyyyyyqqqqwEErTXZ => 2q8w5e2rt5y4qw2ErTXZ
aaa => 3a
abc => abc
a => a