String Compression Algorithm
Medium
string
compression
run-length-encoding
optimization
Problem Description
Implement a string compression algorithm using run-length encoding. Compress consecutive identical characters into the format "character + count". If compression doesn't reduce length, return original string.
Input Format
A single string containing letters.
Output Format
Compressed string if shorter, otherwise original string.
Constraints
• 1 ≤ string length ≤ 1000
• String contains only uppercase and lowercase letters
• Format: character followed by count (e.g., a3b2c1)
• Single characters become char1 (e.g., a becomes a1)
• Return original if compressed is not shorter
Sample Input/Output
Input:
aabcccccaaa
Output:
a2b1c5a3
Explanation
Original: "aabcccccaaa" (11 chars). Compressed: "a2b1c5a3" (8 chars). Compression is shorter, so return compressed.
Solution Hints
75
Points
Points
1500ms
Time Limit
Time Limit
128MB
Memory Limit
Memory Limit
Code Editor
Register to Access Code Editor
Create a free account to solve coding problems and track your progress.
Register Now