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);
}
}
Example run
Enter a string: qqqqWWWr
RESULT: "117q90Wr"