Runlength encoding is a simple compression scheme best used

Run-length encoding is a simple compression scheme best used when a data-set consists primarily of numerous, long runs of repeated characters. For example, AAAAAAAAAA is a run of 10 A’s. We could encode this run using a notation like *A10, where the * is a special flag character that indicates a run, A is the symbol in the run, and 10 is the length of the run. As another example, the string would be encoded

KKKKKKKKKKKKKBCCDDDDDDDDDDDDDDDKKKKKMNUUUGGGGG $K13BCC$D15$K5MNUUU$G5

assuming in this case that $ is the flag character. For the sake of this problem we will assume that the input strings to be encoded contain only uppercase letters from the Latin alphabet and that no run is longer than 99 characters long. Note that single letters, runs of two letters, and runs of three letters are not encoded, as doing so does not save memory or actually compress the data. Do you see why that is the case?

Write a method

that takes a string consisting of uppercase letters only and returns the run-length encoded input string. Below are sample runs of the program showing how input and output must be formatted by your program.

Example 1:

encode(‘‘XYZAAAAAAGGTCCCCCCTTTAAAAAAAAAAAAAAKK’’, ‘*’) Return: ‘‘XYZ*A6GGT*C6TTT*A14KK’’

,

Solution

public class Test{
   public static String encode(String message, char delimiter){
       String output = \"\";
       int count = 1;
       char lastChar = message.charAt(0);
       for(int i = 1; i < message.length(); i++){
           char temp = message.charAt(i);
           // System.out.println(temp);
           if(temp == lastChar){
               count++;
           }
           else{
               if(count > 3){
                   output += \"\" + delimiter + lastChar + count;
                   count = 1;
               }
               else{
                   for(int j = 0; j < count; j++) output += lastChar;
                   count = 1;
               }
               lastChar = temp;
           }
       }
       if(count > 3){
           output += \"\" + delimiter + lastChar + count;
           count = 1;
       }
       else{
           for(int j = 0; j < count; j++) output += lastChar;
           count = 1;
       }
       return output;
   }
   public static void main(String args[]){
       System.out.println(encode(\"XYZAAAAAAGGTCCCCCCTTTAAAAAAAAAAAAAAKK\", \'*\'));
   }
}

Run-length encoding is a simple compression scheme best used when a data-set consists primarily of numerous, long runs of repeated characters. For example, AAAA
Run-length encoding is a simple compression scheme best used when a data-set consists primarily of numerous, long runs of repeated characters. For example, AAAA

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site