Intermediate Level

Implement the method compressRuns that compresses consecutive repeated characters.

Replace each consecutive run with the character followed by the number of times it appears in that run.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Single characters still receive a count of 1.
  • Preserve the original order of runs.
  • The test cases use visible characters without spaces.
Example 1
Input:
s (string) = aaabbc
Return:
(string) a3b2c1
Example 2
Input:
s (string) = abcd
Return:
(string) a1b1c1d1
Example 3
Input:
s (string) = zzzz
Return:
(string) z4

Track the current character and run length. Append the previous run whenever the character changes.

Run your code to see the result.