LeetCode: String Compression
Compress strings in place using counts of repeated characters.
See original problem on leetcode.com
Difficulty: Medium
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)