Compress a String Using Run-Length Encoding

Implement compressString

Given a string s, compress it using run-length encodingRun-Length EncodingA simple compression scheme that replaces each run of consecutive identical characters with the character followed by how many times it repeats — "aaabbc" becomes "a3b2c".: every run of consecutive identical characters becomes that character followed by the run's length, unless the run has length 1, in which case just the character is written with no count. Building the compressed result by repeatedly concatenating onto a plain string works, but in most languages a string is immutable — every += allocates a brand new string and copies everything built so far into it, turning n appends into O(n²) work. Appending to a mutable builder instead (a StringBuilder, a list joined at the end, or a pre-sized buffer) keeps each append O(1) amortized, bringing the whole pass down to O(n).

Example 1:

Input: s = "aaabbc"

Output: "a3b2c"

Example 2:

Input: s = "abc"

Output: "abc"

Example 3:

Input: s = "aabbcc"

Output: "a2b2c2"

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ s.length ≤ 2000
  • s consists only of lowercase English letters

s =

aaabbc