(python3) 字符串壓縮與解壓

題目贅述:git

本題須要你根據壓縮或解壓的要求,對給定字符串進行處理。這裏咱們簡單地假設原始字符串是徹底由英文字母和空格組成的非空字符串。spa

輸入格式:code

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

 

輸出格式:字符串

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

輸入樣例 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
題目解析:string

題目不難,對字符串的處理問題。首先必定是分兩種狀況。。it

看以下解答,感受可讀性還不錯。class

壓縮的思路是尋找連續相同的字符,輸出「計數」「字符」,計數爲1時省略數字,重點是如何使遍歷過程不重複、不遺漏,對於i 的操做尤其關鍵;遍歷

解壓的思路是找數字及其後的字符,沒有數字直接copy,難點還是遍歷過程,且數字多是一位數到三位數。

 

pro = input()
string = input()
n = len(string)
ans=""                  # 輸出結果
if pro == "C":          # 壓縮
    i = 0
    while i < n:        # 從i 開始尋找連續相同的字符,計數爲con
        j = i+1
        con = 1
        while j < n and string[j]== string[i]:
            con += 1
            j += 1
        if con == 1:      # 計數爲1 則直接加到ans
            ans = ans + string[i]
        else:
            new = "%d%s" % (con, string[i])
            ans = ans + new
        i = j             # i 定位到下一個字符
 
else:                    # 解壓
    i=0
    while i < n:
        j = i + 1
        if string[i].isdigit():            # 從i 開始尋找連續的數字字符,爲數量num
            while string[j].isdigit():
                j+=1
            num = int(string[i:j])
            new = string[j] * num
            ans = ans + new
            i = j + 1
        else:                               # 若i 不爲數字,直接添加到ans
            ans = ans + string[i]
            i = j
print(ans)
相關文章
相關標籤/搜索