Run-length encoding is a relatively simple technique for compressing data; if a
ID: 3585231 • Letter: R
Question
Run-length encoding is a relatively simple technique for compressing data; if a particular value (or substring) appears multiple times in a row, it is only represented once, followed by an integer indicating the number of times it should be repeated. For example, the string "AAAAA" can be compressed to "A5" (5 occurrences of 'A'), saving three characters in the process. Define a Java method named expand() that takes a single String argument. You may assume that this String is run-length encoded and contains an even number of characters (each pair of characters consists of a printing character followed by a single digit representing its repetition count). Your method should return a new String that contains the expanded (or decoded) version of its argument. For example, calling expand("a3b7a2c4") would return the String "aaabbbbbbbaacccc". Complete this problem by writing a complete Java program that prompts the user to enter a run-length encoded string, passes it to your expand () method, and displays the decoded result. Hint: Java's Integer.parseInt ) method may be helpful here if you want to avoid performing character arithmetic.Explanation / Answer
ExpandTest.java
import java.util.Scanner;
public class ExpandTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string: ");
String s = scan.next();
System.out.println("Expanded String is "+expand(s));
}
public static String expand(String s) {
String str = "";
for(int i=0;i<s.length();i++) {
if(i % 2 != 0) {
int n = Integer.parseInt(s.charAt(i)+"");
char ch = s.charAt(i-1);
for(int j=0;j<n;j++) {
str+=ch;
}
}
}
return str;
}
}
Output:
Enter the string:
a3b7a2c4
Expanded String is aaabbbbbbbaacccc
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.