问题: 游程编码 (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/