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

Write your code in the file StringRec.java. For this problem, the following rest

ID: 3580335 • Letter: W

Question

Write your code in the file StringRec.java. For this problem, the following restrictions apply:

YOUR CODE MUST BE RECURSIVE.

Do not use loops (while, do/while, or for).

Do not declare any variables outside of a method. You may declare local variables inside a method.

Complete the following method:

public static String compress(String compressedText): Decompress the input text, which has been compressed using the RLE algorithm

So, input: qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT

output: q9w5e2rt5y4qw2Er3T

Explanation / Answer

import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
public static String compress(String compressedText)
{
if (compressedText.length() <= 1) return compressedText;

int runLength = 1;
//count next character with previous char weather they are same, if same then increase runLength
while (runLength < compressedText.length() && compressedText.charAt(0) == compressedText.charAt(runLength))
{
runLength++;
}

String lengthString = runLength > 1 ? String.valueOf(runLength) : "";
//append no of occurence of character runLength and character and call recursive function
//with string after runLength characters
return lengthString + compressedText.substring(0,1) + compress(compressedText.substring(runLength));
}
   public static void main (String[] args) throws java.lang.Exception
   {
       //string to take input
       String s = "qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT" ;
       System.out.printf("Input: %s ",s);
       System.out.printf("Output: %s ",compress(s) );
   }
}

-----------------------------------------------------------------------------------------------------------

output:

Input: qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT
Output: q9w5e2rt5y4qw2Er3T