Question & Answer: Run Length Encoding Implement run-length encoding on strings. Run-length encoding collapses consecutive insta…..

☆ Run Length Encoding Implement run-length encoding on strings. Run-length encoding collapses consecutive instances of a single character into two pieces of information: the Note that even single characters should be run length encoded. If the string is empty, return an empty string Your implementation should work on all alphanumeric characters Complete the runlengthEncode function which takes a string input as a parameter and returns the compressed string Sample Input GGGGGrmrrrrt Sample Output 5G14r1t t There are 5 G·characters then there are 14 rs then there is

Run Length Encoding Implement run-length encoding on strings. Run-length encoding collapses consecutive instances of a single character into two pieces of information: the number of instances and the Note that even single characters should be run length encoded. If the string is empty, return an empty string Your implementation should work on all alphanumeric characters. Complete the runlengthEncode function which takes a string input as a parameter and returns the compressed string. Sample Input GGGGGrmrrrrrrrrrrrrrrt Sample Output 5G14r1t Explanation There are 5 ‘G’ characters then there are 14 ‘r’ s then there is 1 ‘t’.

Expert Answer

 

package sample1;

import java.util.Scanner;

class RunLengthEncoding{

public static void main(String args[]) {

String input = null;

Scanner s = new Scanner(System.in);

System.out.println(” enter a string :”);

input = s.nextLine();

System.out.println(” Encoded string : ” + runLengthEncoding(input));

}

public static String runLengthEncoding(String input) {

String output = “”;

for (int i = 0; i < input.length(); i++) {

if (output.indexOf(input.charAt(i)) == -1 ){

output = output + findNumOccurences(i, input.charAt(i), input) + input.charAt(i) ;

}

}

return output;

}

public static int findNumOccurences(int startIndex, char ch, String input) {

int count = 1;

for (int i = startIndex + 1; i < input.length(); i++) {

if (ch == input.charAt(i)) {

++count;

}

}

return count;

}

}

Output:

Still stressed from student homework?
Get quality assistance from academic writers!