-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathString Compression.py
More file actions
33 lines (25 loc) · 816 Bytes
/
String Compression.py
File metadata and controls
33 lines (25 loc) · 816 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
32
33
from typing import List
class Solution:
"""
Time: O(n)
Memory: O(1)
"""
def compress(self, chars: List[str]) -> int:
n = len(chars)
walker = runner = 0
while runner < n:
# Write the current character to a new position
chars[walker] = chars[runner]
count = 1
# Count the number of repetitions of the current character
while runner < n - 1 and chars[runner] == chars[runner + 1]:
runner += 1
count += 1
# If the current character is repeated more than once
if count > 1:
for d in str(count):
walker += 1
chars[walker] = d
runner += 1
walker += 1
return walker