Skip to content

Latest commit

 

History

History
55 lines (40 loc) · 1.25 KB

_443. String Compression.md

File metadata and controls

55 lines (40 loc) · 1.25 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : November 04, 2024

Last updated : November 04, 2024


Related Topics : Two Pointers, String

Acceptance Rate : 57.35 %


Solutions

Python

class Solution:
    def compress(self, chars: List[str]) -> int:
        output_len = 0
        prev, cnt = None, 0
        output_len = 0

        # + [None] allows for the last round of characters
        #          to have a turn to be added
        for c in chars + [None] :
            if prev == c :
                cnt += 1
                continue

            if prev :
                chars[output_len] = prev
                output_len += 1

                reps_str = str(cnt)
                if cnt > 1 :
                    for x in reps_str :
                        chars[output_len] = x
                        output_len += 1
            prev = c
            cnt = 1

        return output_len