编写 C++ 代码,将字符串 AAABCDEFOOOOOO 转换为 (3)A(-5)BCDEF(6)O

问题描述 投票:0回答:1

我写了代码,但我不明白为什么会发生这种情况,以至于它在不同的字母(-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

我尝试把柜台放在其他地方,但它没有给我我想要的东西。

c++
1个回答
0
投票

在您的帖子中需要指出的一些基本事项:

  1. 请校对您写的第一句话。如果你读过它;感觉不清楚
    (-5)BCDEF
    还是
    (-1)B(-1)C(-1)D(-1)E(-1)F
    是你想要的。必须经历几次才能理解。
  2. 您应该快速查看最小可复制示例指南
    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
上。

© www.soinside.com 2019 - 2024. All rights reserved.