String Compression

Medium~15 min

Implement basic string compression using the counts of repeated characters.

For example, the string "aabcccccaaa" would become "a2b1c5a3".

If the compressed string would not become smaller than the original string, return the original string. You can assume the string has only lowercase and uppercase English letters.

Note that consecutive runs of the same character are compressed independently. The string "aabaa" becomes "a2b1a2", not "a4b1".

Examples

Example 1
Input: s = "aabcccccaaa"
Output: "a2b1c5a3"
Explanation: a appears 2 times, b appears 1 time, c appears 5 times, a appears 3 times.
Example 2
Input: s = "abcdef"
Output: "abcdef"
Explanation: Compressed would be "a1b1c1d1e1f1" (12 chars) which is longer than the original (6 chars), so return the original.
Example 3
Input: s = "aaaa"
Output: "a4"
Explanation: Compressed "a4" (2 chars) is shorter than "aaaa" (4 chars).

Constraints

  • 0 <= s.length <= 10^4
  • s contains only English letters (uppercase and lowercase)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run