A program to do basic string compression. For a character that is consecutively repeated more than once, replace consecutive duplicate occurrences with the count of repetitions. In C++ language.
If a string has 'x' repeated 5 times, replace this "xxxxx" with "x5".
The string is compressed only when the repeated character count is more than 1.
Code:- #include <bits/stdc++.h>
using namespace std;
string getCompressedString(string &input) {
if (input.length() == 0)
return "";
// Variables to iterate the string and keep the count of the current character.
int startIndex = 0;
int endIndex = 0;
// Resultant string.
string compressedString = "";
// Iterate all the characters of the string.
while (startIndex < input.length()) {
while ((endIndex < input.length()) && (input[endIndex] == input[startIndex]))
{
endIndex += 1;
}
int totalCharCount = endIndex - startIndex;
// If count is greater than 1, then append count to the string, else only character.
if (totalCharCount != 1)
{
compressedString += input[startIndex];
compressedString += (char)(totalCharCount + '0');
}
else
{
compressedString += input[startIndex];
}
startIndex = endIndex;
}
return compressedString;
}
int main() {
int size = 1e6;
string str;
cin >> str;
str = getCompressedString(str);
cout << str << endl;
}
aaabbcddeeeee
Output
a3b2cd2e5
Submitted by ARYA CHANDRAKAR (Arya)
Download packets of source code on Coders Packet
Comments