c++ - 在 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。
解决方案
for (int i = 0; i <= str.length(); i++)
应该
for (int i = 0; i < str.length(); i++)
在 C++ 中,字符串索引从零开始,在字符串长度之前结束一。
推荐阅读
- asp.net-mvc - 从 Microsoft 身份平台获取刷新令牌
- java - 使用 Kafka Avro 序列化程序和自动生成处理 Java 8 LocalDate
- javascript - Query.swap 向后兼容性
- dart - dart 项目(Aqueduct)中包含自定义文件(json、txt)的文件夹
- php - 可以从 CakePHP 2.8 迁移到 4.x
- bash - 为什么“test -e”在我的 bash 脚本中不能正常工作?
- python - 除数时Python计算器错误
- c++ - 在 C++ 中连接内存块
- angular - 如何在角度 8 中为 viewchild 元素引用编写点击事件
- go - Golang http 客户端被重定向到登录 bitbucket 私有 URL,而不是提供身份验证失败