首页 > 解决方案 > 在 C++ 中编写运行长度编码器的困难

问题描述

尝试编写此运行长度编码器,它基本上可以工作,但由于“/ 0”,它没有通过测试用例。

代码

std::string run_length_encode(const std::string& str)
{
    std::string encoded = "";
    char prevch;
    char newch;
    int count = 1;
    prevch = str[0];
    for (int i = 0; i <= str.length(); i++)
    {
        newch = str[i];
        if (prevch == newch)
        {
            count++;
        }
        else
        {
            encoded += prevch;
            if (count > 1)
            {
                encoded += std::to_string(count);
            }
            prevch = newch;
            count = 1;
        }
    }
    if (prevch == newch)
    {
        encoded += newch;
        if (count > 1)
        {
            encoded += std::to_string(count);
        }
    }
    return encoded;

错误信息:

Expected equality of these values:
  run_length_encode("A")
    Which is: "A\0"
  "A"

答案应该是 A,但我的代码返回 A\0。

标签: c++run-length-encoding

解决方案


for (int i = 0; i <= str.length(); i++)

应该

for (int i = 0; i < str.length(); i++)

在 C++ 中,字符串索引从零开始,在字符串长度之前结束一


推荐阅读