174. String Compression (Run-Length Encoding)

EasyStringString

Given a string s, compress it using run-length encoding.

For each group of consecutive repeating characters, output the character followed by the count if count > 1, or just the character if count == 1.

Example: 'aabcccccaaa' → 'a2bc5a3'

Input: A single string s.

Output: The run-length encoded string.

Examples

Example 1
Input: aabcccccaaa
Output: a2bc5a3
Explanation: aa→a2, b→b, ccccc→c5, aaa→a3.
Example 2
Input: abc
Output: abc
Explanation: No repeats; each char count=1 so no digit appended.
Example 3
Input: aaabba
Output: a3b2a
Explanation: aaa→a3, bb→b2, a→a.

Constraints

Asked by

PaytmAmazonAppleBloombergMicrosoftAccenture
Solve this problem in the editor →