Compress String with Limited Repetition
Given a string consisting of lowercase alphabetic characters, compress the string by replacing consecutive repeated characters with the character followed by the count of its repetitions.
However, to keep the count readable, if the count of consecutive repeated characters exceeds 9, split the count into chunks of at most 9.
If a character appears only once consecutively, do not append a count after it.
Input
- A string
strcontaining only lowercase English letters (a-z). - Length of
stris between0and10^5.
Output
- A compressed string where consecutive repeated characters are replaced by the character followed by the count, with no count larger than 9.
- Single occurrences of a character are left as-is (no trailing
1).
Examples
-
Input:
"aaabbbccccccccccc"Output:"a3b3c9c2"Explanation:'a'is repeated 3 times →"a3"'b'is repeated 3 times →"b3"'c'is repeated 11 times → split as"c9c2"(since count can't exceed 9)
-
Input:
"xxxxxxxxxxxx"Output:"x9x3"Explanation:'x'is repeated 12 times → split as"x9x3"
-
Input:
"abc"Output:"abc"Explanation:- No characters are repeated consecutively, so the string is returned as-is.
-
Input:
"aabbccddeeeeee"Output:"a2b2c2d2e6"Explanation:- Each character is repeated consecutively and count is ≤ 9, so just append the count directly.
Edge Cases
- Empty string input should return an empty string.
- Very long sequences of the same character must correctly split counts into chunks of 9 or less.
- Strings with no consecutive repeats remain unchanged.
- Single character input returns the character itself.
Companies:
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
