Java运行长度编码 [英] Java Run Length Encoding
问题描述
运行长度编码正在使用重复出现字符的字符串,例如qqqqqWWWWr,并将其转换为5q4Wr。重复出现的角色之前应该是连续重现的次数。如果它只发生一次,它不应该在一个数字之前。
Run Length Encoding is taking a string with reoccurring characters, for example qqqqqWWWWr, and transforming it to 5q4Wr. The reoccurring character should be preceded with the amount of times it reoccurs consecutively. If it only occurs once in a row it should not be preceded by a number.
这是我到目前为止,我似乎无法让它正常工作:
Here is what I have so far, and I cannot seem to get it to work properly:
public class Compress {
public static void main(String[] args) {
System.out.print("Enter a string: ");
String s = IO.readString();
int currentRunLength = 1;
String compressedString = "";
for (int i = 0; i < s.length(); i++) {
if (i == s.length() - 1){
if (currentRunLength == 1) {
compressedString += s.charAt(i);
break;
} else {
compressedString += currentRunLength + s.charAt(i);
break;
}
}
if (s.charAt(i) == s.charAt(i + 1)) {
currentRunLength++;
}
if (s.charAt(i) != s.charAt(i + 1) && currentRunLength > 1) {
compressedString += currentRunLength + s.charAt(i);
currentRunLength = 1;
}
if (s.charAt(i) != s.charAt(i + 1) && currentRunLength == 1) {
compressedString += s.charAt(i);
}
}
IO.outputStringAnswer(compressedString);
}
}
示例运行
输入一个字符串:qqqqWWWr
Example run
Enter a string: qqqqWWWr
结果:117q90Wr
RESULT: "117q90Wr"
推荐答案
问题与这一行有关:
compressedString += currentRunLength + s.charAt(i)
这样做是采取 int
并添加它将 char
(将导致 int
),然后将其添加到压缩字符串。
What this is doing is taking int
and adding it to char
(which will result in an int
), then adding it to the compressed string.
您可以通过这个小的更改来解决这个问题,将 currentRunLength
转换为String,然后附加 char
:
You can address that with this minor change, which will convert currentRunLength
to a String, then append the char
:
compressedString += String.valueOf(currentRunLength) + s.charAt(i)
这篇关于Java运行长度编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!