【问题标题】:Difficulty writing run length encoder in c++在 C++ 中编写运行长度编码器很困难
【发布时间】:2020-03-31 21:30:25
【问题描述】:

尝试编写这个运行长度编码器,它基本上可以工作,但由于“/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


    【解决方案1】:
    for (int i = 0; i <= str.length(); i++)
    

    应该是

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

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

    【讨论】:

    • 因为 C++ 数组和字符串是 0-indexed
    猜你喜欢
    • 2011-03-20
    • 1970-01-01
    • 2016-12-24
    • 2018-10-05
    • 1970-01-01
    • 2013-02-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多