字符串的压缩与解压缩答案

James 2025-02-06 17:23:54

#include <bits/stdc++.h>
using namespace std;

// 压缩函数
string compress(const string& s) {
    string compressed;
    int count = 1;
    for (int i = 0; i < s.length(); ++i) {
        if (i + 1 == s.length() || s[i] != s[i + 1]) {
            compressed += s[i];
            compressed += to_string(count);
            count = 1;
        } else {
            count++;
        }
    }
    return compressed.length() < s.length() ? compressed : s;
}

// 解压缩函数
string decompress(const string& s) {
    string decompressed;
    for (int i = 0; i < s.length(); i += 2) {
        char c = s[i];
        int count = s[i + 1] - '0';
        for (int j = 0; j < count; ++j) {
            decompressed += c;
        }
    }
    return decompressed;
}

int main() {
    string input;
    cin >> input;

    // 压缩字符串
    string compressed = compress(input);
    // 解压缩字符串
    string decompressed = decompress(compressed);

    // 输出结果
    cout << compressed << endl;
    cout << decompressed << endl;

    return 0;
}

compress 函数

    • 该函数接收一个字符串 s 作为输入,用于将字符串进行压缩。
    • 使用一个变量 count 来记录当前字符连续重复的次数,初始值为 1。
    • 遍历字符串 s,如果当前字符和下一个字符不同,或者已经到达字符串末尾,则将当前字符和重复次数添加到压缩后的字符串 compressed 中,并将 count 重置为 1。
    • 如果当前字符和下一个字符相同,则 count 加 1。
    • 最后,如果压缩后的字符串长度小于原字符串长度,则返回压缩后的字符串;否则返回原字符串。

decompress 函数

    • 该函数接收一个压缩后的字符串 s 作为输入,用于将其解压缩。
    • 遍历压缩后的字符串,每次取两个字符,第一个字符是原字符串中的字符,第二个字符是该字符的重复次数。
    • 将该字符重复相应的次数,并添加到解压缩后的字符串 decompressed 中。