我写了代码,但我不明白为什么会发生这种情况,以至于它在不同的字母(-1)之前给出,并且不计数,然后立即写出所有内容“(-5)BCDEF”。请帮助我。
#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;
}
结果:
压缩前:
AAABCDEFOOOOOO
(3)A(-1)B(-1)C(-1)D(-1)E(-1)F(6)O
0.424242
我尝试把柜台放在其他地方,但它没有给我我想要的东西。
(-5)BCDEF
还是 (-1)B(-1)C(-1)D(-1)E(-1)F
是你想要的。必须经历几次才能理解。reservedstring
不执行任何操作,删除将使您和其他调试器的工作更轻松。查看您的问题规范,您希望累积负的连续出现次数(不同的值),而不仅仅是正的。在您的代码中,仅当相同的字符连续出现时才会累积。 我的第一直觉是循环之前的布尔变量:
bool changed_last = true
还可以编辑你的 if:
if (input[i] == currentChar) {
count++;
}
要使用此变量并累积负值:
if (input[i] == currentChar || (input[i] != currentChar && changed_last)) {
count++;
currentChar = input[i]; //Now this is necessary
}
现在这个
if
应该正确捕获连续的更改并将它们累积在 count
上。