Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

llaRun-length encoding (RLE) is often regarded as the simplest form of loss less

ID: 3745139 • Letter: L

Question

 llaRun-length encoding (RLE) is often regarded as the simplest form of loss less data compression in which runs of data (that is, sequences where in the same data value occurs repeatedly in consecutive positions) are stored as a single data value and count, rather than the stretched-out raw form.
 In this exercise, you will be writing a string-based implementation of RLE. For a string which consists of duplicate characters placed in neighbouring positions, replace the duplicates with the count of repetitions. e.g. If in a String, the character `x` runs for 5 positions, then replace this `"xxxxx"` with `"x5"`.   create a class `CompressString` that reads in the string to be compressed from the console  and then on a new line, prints the compressed version of the input.  `Note: ` The input string can contain any characters (including blank) except for digits 

Explanation / Answer

Please find below the complete solution to your problem :

class CompressString {  

public static void main(String[] args) {
String str;  
Scanner in = new Scanner(System.in);
//String str = "xxxxx";
System.out.println("Enter a string to be compressed : ");
str = in.nextLine();
char[] arr = str.toCharArray();
int count = 1;
StringBuilder s = new StringBuilder();
char prev = arr[0];

for (int i = 1; i < arr.length; i++) {
char curr = arr[i];
prev = arr[i - 1];
if (curr == prev) {
count++;
} else {
if (count < 2) {
s.append(prev);
} else {
s.append(prev).append(count);
count = 1;
}
}
}

if (count < 2) {
s.append(prev);
} else {
s.append(prev).append(count);
}

System.out.println("Compressed : " + s.toString());

}
}