-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0443-string-compression.py
More file actions
31 lines (25 loc) · 841 Bytes
/
0443-string-compression.py
File metadata and controls
31 lines (25 loc) · 841 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# time complexity: O(n)
# space complexity: O(1)
from typing import List
class Solution:
def compress(self, chars: List[str]) -> int:
count = 1
left = 0
for right in range(1, len(chars) + 1):
if right < len(chars) and chars[right - 1] == chars[right]:
count += 1
else:
chars[left] = chars[right - 1]
left += 1
if count > 1:
for c in str(count):
chars[left] = c
left += 1
count = 1
return left
chars = ["a", "a", "b", "b", "c", "c", "c"]
print(Solution().compress(chars))
chars = ["a"]
print(Solution().compress(chars))
chars = ["a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"]
print(Solution().compress(chars))