LeetCode: String Compression

Compress strings in place using counts of repeated characters.

Posted on LeetCode Python

Solution

I’m rather proud of this one. 😊

Runtime

0 ms | Beats 100.00%

class Solution:
def compress(self, chars: List[str]) -> int:
prev = None
count = 1
i = 0
while i < len(chars):
if prev == chars[i]:
count += 1
chars.pop(i)
else:
if count > 1:
chars[i:len(str(count))] = str(count)
i += len(str(count))
prev = chars[i]
count = 1
i += 1
if count > 1:
chars[i:len(str(count))] = str(count)
return len(chars)