Java: Run-length encoding

Run-length encoding shrinks text with long runs of the same character. Write both directions with StringBuilder.

What to build

A program that encodes and decodes run-length text.

Requirements

  • Each line is e TEXT or d CODE. For e, print the encoding: each run as the character followed by its length, such as aaabcc → a3b1c2.
  • For d, print the decoded text, such as x12y1 → twelve x's then a y.

Input

Line 1: n. Then n lines.

Output

n lines.

Constraints

1 ≤ n ≤ 50; texts have only letters and at most 500 characters; decoded texts have at most 2000 characters.

Example

Input:

2
e aaabcc
d x3y1z2

Output:

a3b1c2
xxxyzz

Why it works

Encoding compares each character with the previous one to find where a run ends, and decoding gathers every digit after a letter, so counts of 10 and more come back correctly.

Examples

Example 1 · Input
2
e aaabcc
d x3y1z2
Expected output
a3b1c2
xxxyzz
Example 2 · Input
1
e abc
Expected output
a1b1c1

Hints

Hint 1

To encode, count how many times each character repeats in a row and append the character and the count.

Hint 2

To decode, read a character, then all the digits after it as one number (counts can be more than 9).

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

public class Main {
    static String encode(String s) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < s.length()) {
            char c = s.charAt(i);
            int j = i;
            while (j < s.length() && s.charAt(j) == c) j++;
            sb.append(c).append(j - i);
            i = j;
        }
        return sb.toString();
    }

    static String decode(String s) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < s.length()) {
            char c = s.charAt(i++);
            int count = 0;
            while (i < s.length() && Character.isDigit(s.charAt(i))) count = count * 10 + (s.charAt(i++) - '0');
            sb.append(String.valueOf(c).repeat(count));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        for (int i = 0; i < n; i++) {
            String[] parts = in.nextLine().split(" ");
            System.out.println(parts[0].equals("e") ? encode(parts[1]) : decode(parts[1]));
        }
    }
}

Lesson: Strings and StringBuilder →