I wrote the code, but I don’t understand why it happens so that it gives out before different letters (-1), and does not count and then writes out everything at once “(-5)BCDEF”
Please help me
#include <iostream>
#include <string>
using namespace std;
string compressString(const string input) {
string compressedString;
string reservedstring;
char currentChar = input[0];
int count = 1;
for (int i = 1; i < input.length(); i++) {
if (input[i] == currentChar) {
count++;
}
else {
if (count > 1) {
compressedString += "(" + to_string(count) + ")" + currentChar;
}
else {
compressedString += "(-" + to_string(count) + ")" + currentChar;
}
currentChar = input[i];
count = 1;
}
}
if (count > 1) {
compressedString += "(" + to_string(count) + ")" + currentChar;
}
else {
compressedString += "(-" + to_string(count) + ")" + currentChar;
}
return compressedString;
}
int main() {
string input = "AAABCDEFOOOOOO";
string compressed = compressString(input);
cout << "Before compression: " << input << endl;
cout << "After compression: " << compressed << endl;
float compressionRatio = (float)input.length() / compressed.length();
cout << "Compression ratio: " << compressionRatio << endl;
return 0;
}
Results:
Before compression: AAABCDEFOOOOOO
After compression: (3)A(-1)B(-1)C(-1)D(-1)E(-1)F(6)O
Compression ratio: 0.424242
I tried to put the counter somewhere else, but it didn’t give me what I wanted.
Данил is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.