【问题标题】:Run length encoding in C++C++ 中的运行长度编码
【发布时间】:2018-10-02 10:20:50
【问题描述】:
#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 = 无效输入

eeeeeeeeeeeeeeeeeeee = 21e

只有当字符连续重复 9 次或更少时,代码才能正常工作。对于 10 及以上的值,输入是其他符号。 例如它保持空白 10,所以如果输入是 'aaaaaaaaaabb',输出只是 'a2b' 而不是 '10a2b'。对于 11 它的输出 ';', 所以如果输入是'aaaaaaaaaaabb',由于某种原因,输出是';a2b'。

所以我的问题是,我如何让所有数字而不是仅从 0 到 9 的后推都起作用?

如果您来到这里,感谢您抽出宝贵时间。 ^^

【问题讨论】:

  • 你能添加适当缩进的代码吗?
  • 那么您认为这是为什么呢?假设 count = 11,你期望 '0' + count 是什么?
  • Mayur,我希望这会更好(我还是个初学者);
  • 关于c++的问题不要使用c标签
  • Jakub,我一开始以为是 11,但我猜不是。

标签: c++ string compression


【解决方案1】:

如果您可以使用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-17
    • 2013-09-27
    • 1970-01-01
    • 2013-02-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多