LeetCode題解(0443):字符串壓縮(Python)

題目:原題鏈接(簡單)

解法 時間複雜度 空間複雜度 執行用時
Ans 1 (Python) O(n) O(n) 92ms (20.75%)
Ans 2 (Python) O(n) O(n) 68ms (89.76%)

LeetCode的Python執行用時隨緣,只要時間複雜度沒有明顯差異,執行用時一般都在同一個量級,僅作參考意義。

解法一:

def compress(self, chars: List[str]) -> int:
    now = None
    num = 0
    ans = ""
    for c in chars:
        if c == now:
            num += 1
        else:
            if now is not None:
                if num > 1:
                    ans += now + str(num)
                else:
                    ans += now
            now = c
            num = 1
    else:
        if num > 1:
            ans += now + str(num)
        else:
            ans += now
    chars.clear()
    chars.extend(list(ans))
    return len(ans)

解法二:

def compress(self, chars: List[str]) -> int:
    if len(chars) == 0:
        return 0
    now = chars[-1]
    num = 1
    for i in range(len(chars) - 2, - 1, -1):
        if chars[i] == now:
            num += 1
            chars.pop(i + 1)
        else:
            if num > 1:
                for j in str(num)[::-1]:
                    chars.insert(i + 2, j)
            now = chars[i]
            num = 1
    else:
        if num > 1:
            for j in str(num)[::-1]:
                chars.insert(1, j)
    return len(chars)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章