Problem · String
Run-Length String Compression
Learn this problemProblem statement
Given a string text, encode each maximal run of equal consecutive characters from left to right.
- Append the run's character once.
- If the run length is greater than
1, append the full length in base 10. - If the run length is exactly
1, append no count.
Return the concatenation of all encoded runs. Return the empty string when text is empty.
Function
compressRuns(text: String) → StringExamples
Example 1
text = "aaabbccccd"return = "a3b2c4d"The maximal runs are aaa, bb, cccc, and d. The singleton contributes only its character.
Example 2
text = ""return = ""An empty input has no runs and produces an empty encoding.
Example 3
text = "zzzzzzzzzzzzx"return = "z12x"The first run demonstrates a multi-digit count. The final singleton x has no count.
Constraints
0 <= text.length <= 200000textcontains printable ASCII characters.- The returned encoding is formed exactly as specified; it does not need to be shorter than the input.