c++ - 这个 RLE 解码函数只解码第一个字符,我做错了什么?

标签 c++

我正在编写一个使用 RLE 算法压缩字符串的简单程序,我成功地编写了编码函数,并认为我也已经找到了解码函数,但它没有给出正确的输出。

string RunLengthDecoding(string input)
{
    string decodedOutput = "";
    int secondIterator = 0;
    for(int firstIterator=0; firstIterator<input.length(); firstIterator++)
    {
        string counter = ""; int letterCoefficient = 0;
        if(!isalpha(input[firstIterator]))
            continue;
        else
        {
            counter = input.substr(secondIterator, firstIterator);
            secondIterator = firstIterator;
            istringstream(counter) >> letterCoefficient;
            for(int i=0; i<letterCoefficient; i++)
                decodedOutput += input[firstIterator];
        }
    }
    return decodedOutput;
}

如果我输入“6A”或实际上是任何数字粘在任何一个单数字符上,它就可以正常工作。 示例:

6A --> AAAAAA, 77B --> BBBBB.....BBBBB 77 times.

但是如果我输入“6A3B”,它会输出“AAAAAA”。或者实际上,任何数字都贴在 A 旁边,任何数字贴在 B 旁边,它仍然只会打印第一个字符作为前缀的次数,完全忽略其后的所有内容。

最佳答案

应该是这样的:

string RunLengthDecoding(string input)
{
    string decodedOutput = "";
    int secondIterator = 0;
    for (int firstIterator = 0; firstIterator<input.length(); firstIterator++)
    {
        string counter = ""; int letterCoefficient = 0;

        if (!isalpha(input[firstIterator]))
            continue;
        else
        {
            counter = input.substr(secondIterator, firstIterator - secondIterator); // Little change here
            secondIterator = firstIterator + 1; // Add one here
            istringstream(counter) >> letterCoefficient;
            for (int i = 0; i<letterCoefficient; i++)
                decodedOutput += input[firstIterator];
        }
    }
    return decodedOutput;
}

请注意,这似乎适用于基本输入,例如“6A3B25C”,但我感觉某些边缘情况会破坏它,因为没有安全检查。

关于c++ - 这个 RLE 解码函数只解码第一个字符,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49205068/

相关文章:

c++ - 当你有一个二维数组(在 C++ 中)时,调用析构函数的正确方法是什么?

c++ - 我应该将乘数声明为常量还是直接使用而不声明?

c++ - 在 deadline_timer 等待时使用 io_service::post (boost)

c++ - 如何在动态小部件中获取 QGraphicsView 的正确位置、宽度和高度

c++ - 您可以在迭代时从 std::forward_list 中删除元素吗?

c++ - 对齐的动态数组和智能指针

c++ - 无法使用 Microsoft Visual Studio 2010 构建我的代码

c++ - c++ 中虚拟静态函数的替代方案?

c++ - 扩展Visual Studio(2010+)项类型处理程序

c++ - 如何抛出文件和行号错误?