Hi I'm attempting to solve this interview question problem:
String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string
"aabcccccaaa"would become"a2b1c5a3". If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).
It would be easy to solve this problem by creating a new string or just printing out the result but I'm trying to come up with an in-place solution. Basically, I'm using string::erase() and string::insert() function. First, I count up the number of characters present and store it in int variable count, then if a number is being repeated, I simply erase it and insert the count value in there. If a character is not being repeated, then I simply insert 1 since the default value of count is set to 1. Here is the code:
string stringCompression(string A) {
int index = 0; char character = ''; int count = 1; string convertInt = ""; int initial_index = 0, length = A.length();
do {
character = A[index];
initial_index = index;
index++;
while (A[index] == character)
{
count++;
index++;
}
convertInt = to_string(count);
if (count == 1)
{
A.insert(index, convertInt);
index++;
}
else
{
A.erase((initial_index+1), (index-1));
A.insert(initial_index+1, convertInt);
index = initial_index + 2;
count = 1;
}
} while (A[index]!='\0');
return A;
}
int main()
{
cout << stringCompression("aabcccccaaa");
}
Output:
a2b1c5
The expected result would be "a2b1c5a3". But the last set of 3 a's do not appear and I tried debugging it. By the values I get this code should work. But strangely, when I debug, the erase() function automatically deletes the last 3 a's even though the values of Index and initial_index appear to be correct. Can someone please explain why this is happening?