背景:
此问题来自“每日编码”问题29。
游程长度编码是一种快速而简单的字符串编码方法。基本思想是将重复的连续字符表示为单个计数和字符。例如,字符串“ AAAABBBCCDAA”将被编码为“ 4A3B2C1D2A”。
实现行程编码和解码。您可以假定要编码的字符串没有数字,并且仅由字母字符组成。您可以假设要解码的字符串有效。
尝试的解决方案:
#include <iostream>
#include <string>
#include <vector>
std::vector<char> run_length(std::string str)
{
std::vector<char> result;
if (str.empty() || str.size() == 1)
{
const char *ch = str.c_str();
result.push_back(*ch);
return result;
}
int count = 1;
for (int i = 1; i < str.size(); ++i)
{
if (str[i] == str[i - 1])
count++;
else
{
if (count > 1)
{
char ch = count;
result.push_back(ch);
}
result.push_back(str[i - 1]);
count = 1;
}
}
if (count > 1)
{
char ch = count;
result.push_back(ch);
}
result.push_back(str[str.size() - 1]);
return result;
}
int main()
{
std::string str = "AAAABBBCCAA";
auto result = run_length(str);
for (auto it : result)
std::cout << it << " ";
std::cin.get();
}
预期输出:
4A3B2C1D2A
实际输出:
A B C A
问题:
为什么我会在实际输出中得到这些奇怪的字符?我相信我的方法的逻辑应该可以解决问题,但是我得到的这些角色是我以前从未见过的。任何建议,不胜感激。
答案 0 :(得分:4)
行
char ch = count;
不正确。
如果count
为4,则ch
初始化为由整数4编码的字符。您需要获取代表数字的字符。您需要'4'
。您可以使用以下代码从count
中获取数字。
char ch = '0' + count;
但是,如果count
大于9,则将不起作用。如果您希望count
大于9,则必须采用其他策略。
答案 1 :(得分:0)
对容器进行一些细微的修改并使用std :: to_string()可以使它完美运行。
// Daily coding problem #29
// Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as
// a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
// Implement run - length encoding and decoding.You can assume the string to be encoded have no digits and consists solely of alphabetic
// characters.You can assume the string to be decoded is valid.
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> run_length(std::string str)
{
std::vector<std::string> result;
if (str.empty() || str.size() == 1)
{
result.push_back(str);
return result;
}
int count = 1;
for (int i = 1; i < str.size(); ++i)
{
if (str[i] == str[i - 1])
count++;
else
{
if (count > 1)
{
result.push_back(std::to_string(count));
}
result.push_back((std::string(1, str[i - 1])));
count = 1;
}
}
if (count > 1)
{
result.push_back(std::to_string(count));
}
result.push_back(std::string(1, str[str.size() - 1]));
return result;
}
int main()
{
std::string str = "AAAAAAAAAABBBCCAA";
auto result = run_length(str);
for (auto it : result)
std::cout << it << " ";
std::cin.get();
}