以C++为单位进行运行长度编码

Run length encoding in C++

本文关键字:编码 运行 C++ 为单位      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string compression(const string & str){
int i = str.size();
string letters;
letters[0] = str[0];
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters.push_back('0' + count);
letters.push_back(str[j]);
}
return letters;
}
int main(){
string input;
char c;
try {
cout << "Enter the data to be compressesed: "<< endl;
cin >> input;
for (int z = 0; z < input.length(); ++z){
c = input.at(z);
}
if (!(c >= 'a' && c <= 'z')){
throw runtime_error("error: invalid input");
}
}
catch (runtime_error& excpt){
cout << excpt.what() <<endl;
return 0;
}
cout << "The compressed data is " << compression(input) << endl;
return 0;
} 

预期的输出是 ,对每组字符重复执行。这是按顺序重复的次数。

一些例子:

aaeeeeae = 2a4e1a1e

rr44errre = 无效输入

eeee = 21e

仅当字符连续重复 9 次或更少时,代码才能正常工作。 对于 10 或更大的值,输入是其他符号。 例如,它在 10 中保持空白,因此如果输入是"aaaabb",则输出只是"a2b"而不是"10a2b"。对于 11 个输出 ';', 因此,如果输入是"aaa出于某种原因,A2B'。

所以我的问题是,我如何使反推适用于所有数字,而不仅仅是从 0 到 9?

如果你来到这里,谢谢你的时间。^^

如果你可以使用 c++11 或更高版本,你的函数compression可能看起来像:

string compression(const string & str){
int i = str.size();
string letters;
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters += std::to_string(count);
letters.push_back(str[j]);
}
return letters;
}