[英]Difficulty writing run length encoder in 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++ 中,字符串索引從零開始並在字符串長度之前的一結束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.