1. 程式人生 > >【PAT乙級】1078 字串壓縮與解壓

【PAT乙級】1078 字串壓縮與解壓

文字壓縮有很多種方法,這裡我們只考慮最簡單的一種:把由相同字元組成的一個連續的片段用這個字元和片段中含有這個字元的個數來表示。例如 ccccc 就用 5c 來表示。如果字元沒有重複,就原樣輸出。例如 aba 壓縮後仍然是 aba

解壓方法就是反過來,把形如 5c 這樣的表示恢復為 ccccc

本題需要你根據壓縮或解壓的要求,對給定字串進行處理。這裡我們簡單地假設原始字串是完全由英文字母和空格組成的非空字串。

輸入格式:

輸入第一行給出一個字元,如果是 C 就表示下面的字串需要被壓縮;如果是 D 就表示下面的字串需要被解壓。第二行給出需要被壓縮或解壓的不超過 1000 個字元的字串,以回車結尾。題目保證字元重複個數在整型範圍內,且輸出檔案不超過 1MB。

輸出格式:

根據要求壓縮或解壓字串,並在一行中輸出結果。

輸入樣例 1:

C TTTTThhiiiis isssss a   tesssst CAaaa as

輸出樣例 1:

5T2h4is i5s a3 te4st CA3a as

輸入樣例 2:

D 5T2h4is i5s a3 te4st CA3a as10Z

輸出樣例 2:

TTTTThhiiiis isssss a   tesssst CAaaa asZZZZZZZZZZ

個人思路

這題就是根據操作型別遍歷待操作字串,然後將遍歷處理的結果加到結果字串上。

本題有一個注意點:

重複字元的個數可能>=10,也就意味著有可能會有兩位及以上的數字出現,因此要正確地在字串和整型數字直接轉換

建議使用sprintf()函式

程式碼實現

#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <cmath>
#include <algorithm>
#include <iostream>
#define ll long long
#define ep 1e-5
#define INF 0x7FFFFFFF

using namespace std;

int main() {
    // 輸入操作碼
    char oper;
    cin >> oper;
    getchar();
    
    // 輸入待操作字串
    string oper_str, ans_str = "";
    getline(cin, oper_str);
    
    int len = int(oper_str.length());
    // 壓縮操作
    if (oper == 'C') {
        for (int i = 0; i < len; i ++) {
            int cnt = 1;
            while (oper_str[i] == oper_str[i+1]) {
                i ++;
                cnt ++;
                if (i == len-1)
                    break;
            }
            if ((i == len-1 && oper_str[i] != oper_str[i-1]) || cnt == 1) {
                ans_str += oper_str[i];
                continue;
            }
            char cnt_str[5];
            sprintf(cnt_str, "%d", cnt); //使用sprintf函式直接將數字轉化成字串
            ans_str += cnt_str;
            ans_str += oper_str[i];
        }
    }
    // 解壓縮操作
    else if (oper == 'D') {
        for (int i = 0; i < len; i ++) {
            int cnt = 0;
            while (oper_str[i] >= '0' && oper_str[i] <= '9') {
                cnt = cnt*10 + (oper_str[i]-'0');
                i ++;
            }
            if (cnt == 0) {
                cnt ++;
            }
            while (cnt --) {
                ans_str += oper_str[i];
            }
        }
    }
    
    cout << ans_str << endl;
    
    return 0;
}

總結

學習不息,繼續加油