解法一:使用哈希表统计字符出现的次数,然后按照ASCII码从大到小的顺序输出。

#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;

string compressString(string str) {
    unordered_map<char, int> count;
    for (char c : str) {
        count[c]++;
    }
    
    vector<pair<char, int>> compressed;
    for (auto it = count.begin(); it != count.end(); ++it) {
        compressed.push_back(make_pair(it->first, it->second));
    }
    
    sort(compressed.begin(), compressed.end(), [](const pair<char, int>& p1, const pair<char, int>& p2) {
        return p1.first > p2.first;
    });
    
    string compressedStr;
    for (auto& p : compressed) {
        compressedStr += p.first;
        compressedStr += to_string(p.second);
    }
    
    return compressedStr;
}

int main() {
    freopen("compress.in", "r", stdin);
    freopen("compress.out", "w", stdout);
    
    string str;
    cin >> str;
    
    string compressedStr = compressString(str);
    cout << compressedStr << endl;
    
    return 0;
}

解法二:使用数组统计字符出现的次数,然后按照ASCII码从大到小的顺序输出。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

string compressString(string str) {
    int count[128] = {0};
    for (char c : str) {
        count[c]++;
    }
    
    vector<pair<char, int>> compressed;
    for (int i = 0; i < 128; i++) {
        if (count[i] > 0) {
            compressed.push_back(make_pair((char)i, count[i]));
        }
    }
    
    sort(compressed.begin(), compressed.end(), [](const pair<char, int>& p1, const pair<char, int>& p2) {
        return p1.first > p2.first;
    });
    
    string compressedStr;
    for (auto& p : compressed) {
        compressedStr += p.first;
        compressedStr += to_string(p.second);
    }
    
    return compressedStr;
}

int main() {
    freopen("compress.in", "r", stdin);
    freopen("compress.out", "w", stdout);
    
    string str;
    cin >> str;
    
    string compressedStr = compressString(str);
    cout << compressedStr << endl;
    
    return 0;
}
``
C++题目描述从电脑输入一个合法的英文字符构成的字符串将这个字符串按照ASCII码从大到小的顺序进行压缩后输出压缩规则是每个字符如果在这个字符串中出现了很多次则输出这个字符再紧接着输出这个字符总共出现的次数。输入描述输入文件:compressin输入一行一个字符串字符串长度不超过1e7输出描述输出文件:compressout属于一行一个字符串表示压缩后的字符串的样式样例1输入abcab输出c1b2

原文地址: https://www.cveoy.top/t/topic/h2xD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录