# Runtime: 64 ms, faster than 20.90% of Python3 online submissions for String Compression.
# Memory Usage: 14 MB, less than 6.25% of Python3 online submissions for String Compression.

class Solution:
    def compress(self, chars: List[str]) -> int:
        count = 1
        lst = []
        last = len(chars) - 1
        for i in range(1, len(chars)):
            if chars[i] == chars[i - 1]:
                count += 1
            else:
                temp = [*lst, chars[i - 1]]
                if count < 9:
                    lst = [*temp] if count == 1 else [*temp, str(count)]
                else:
                    count = list(str(count))
                    lst = [*temp, *count]
                count = 1

        temp = [*lst, chars[last]]
        if count < 9:
            lst = [*temp] if count == 1 else [*temp, str(count)]
        else:
            count = list(str(count))
            lst = [*temp, *count]

        for j in range(len(lst)):
            chars[j] = lst[j]
        return len(lst)

https://leetcode.com/problems/string-compression/

0개의 댓글