
Problem
Solution
Submissions
String Compression Algorithm
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to implement a basic string compression algorithm. The algorithm should replace consecutive repeated characters with the character followed by the count of repetitions. If the compressed string is not smaller than the original string, return the original string.
Example 1
- Input: s = "aabcccccaaa"
- Output: "a2b1c5a3"
- Explanation:
- "aa" becomes "a2"
- "b" becomes "b1"
- "ccccc" becomes "c5"
- "aaa" becomes "a3"
Example 2
- Input: s = "ab"
- Output: "ab"
- Explanation:
- "a" becomes "a1" and "b" becomes "b1"
- The compressed string "a1b1" is longer than the original string "ab"
- So we return the original string.
Constraints
- 1 ≤ s.length ≤ 1000
- s consists of lowercase English letters only
- Time Complexity: O(n), where n is the length of the string
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Iterate through the string and count consecutive characters.
- Build the compressed string using a StringBuilder for efficiency.
- Compare the length of the compressed string with the original.
- Handle edge cases like empty strings or strings with no compression.