Compress a string by replacing consecutive repeated characters with the character followed by its count. For example, "aabbbcc" becomes "a2b3c2". If the compressed string is not shorter than the original, return the original string. Return null for null input and empty string for empty input.
Examples:
Input: str = 'aabbbcc'
Output: 'a2b3c2'
Explanation: a appears 2 times, b appears 3 times, c appears 2 times
Input: str = 'abc'
Output: 'abc'
Explanation: Compressed would be 'a1b1c1' which is longer, so return original
Input: str = 'aaa'
Output: 'a3'
Explanation: a appears 3 times, compressed is shorter
Input: str = null
Output: null
Explanation: Null input returns null
Input: str = ''
Output: ''
Explanation: Empty string returns empty string
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay July 2026
Contest runs July 1 - 31. Complete challenges to climb the leaderboard!
Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.