Problem Statement
To reduce the size of messages transmitted over the internet, a compression algorithm encodes consecutive repeating characters in a string.
Implement this compression:
- Scan the string left to right and group consecutive identical characters
- If a character appears once, add just the character to the output
- If a character appears more than once consecutively, add the character followed by the count of consecutive occurrences
Constraints
1 <= s.length <= 10^5sconsists of lowercase English letters only
Example
Input: "aaaaabbbccca"
Output: "a5b3c3a"
Explanation:
aaaaa→a5(5 consecutive a's)bbb→b3(3 consecutive b's)ccc→c3(3 consecutive c's)a→a(single a, no number)
Input: "abcdef"
Output: "abcdef" (no consecutive repeats)
Input: "aabbaabb"
Output: "a2b2a2b2"
Follow-ups
- What if the count itself is multi-digit (e.g., 12 consecutive chars)? Does your encoding still decode uniquely?
- Can the compressed string ever be longer than the input? When?
- How would you implement the decompression function?
- What's the worst-case compression ratio?