Compress String (Character Count)
C++
Hard
5 views
Problem Description
Compress string by showing character and its count. "aaabbc" -> "a3b2c1"
Real Life: Data compression basics.
Step-by-Step Logic:
1. Count consecutive same characters
2. Write character and its count
3. Move to next different character
4. Return compressed string
Official Solution
void string_q14_compress_string() {
string text = "aaabbccccdd";
string compressed = "";
cout << "Original: " << text << endl;
int i = 0;
while(i < text.length()) {
char current = text[i];
int count = 0;
// Count consecutive same characters
while(i < text.length() && text[i] == current) {
count++;
i++;
}
compressed += current;
compressed += to_string(count);
}
cout << "Compressed: " << compressed << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!