69. Squash the Runs

A compression tool shortens a string by replacing every run, a maximal block of one repeated character, with that character followed by the length of the run written in decimal. A run of length 1 is also written with its count.

Given the string s, return its compressed form. For example, "aaab" becomes "a3b1". Runs longer than 9 use all their digits.

Example 1

Input:
s = "wwwxyy"
Output:
"w3x1y2"
Explanation:

The runs are www, x and yy, which are written as w3, x1 and y2.

Example 2

Input:
s = "kkkkkkkkkkkk"
Output:
"k12"
Explanation:

One run of twelve k characters is written as k12.

Constraints

1 ≤ s.length ≤ 105

s contains only lowercase English letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…