Skip to content

Latest commit

 

History

History
34 lines (25 loc) · 825 Bytes

443.md

File metadata and controls

34 lines (25 loc) · 825 Bytes

443 String Compression

Description

link


Solution

  • See Code

Code

O(n) O(1)

class Solution:
    def compress(self, chars: List[str]) -> int:
        left = i = 0 # 每发现一段新的重复字符块left就向前移动一位
        while i < len(chars):
            char, length = chars[i], 1
            while (i + 1) < len(chars) and char == chars[i + 1]: # 如果重复并且没有到底末尾
                length, i = length + 1, i + 1
            chars[left] = char # 替换chars的内容
            if length > 1:
                len_str = str(length)
                chars[left + 1:left + 1 + len(len_str)] = len_str
                left += len(len_str)
            left, i = left + 1, i + 1
        return left