-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path443. String Compression.py
More file actions
52 lines (45 loc) · 1.5 KB
/
443. String Compression.py
File metadata and controls
52 lines (45 loc) · 1.5 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution:
def compress1(self, chars: List[str]) -> int:
# i: index to read; j: index to write
j = 0
count = 1
def _appendCharCount(ch, count):
nonlocal j
#print ('_appendCharCount, j:', j, ' i:', i, ' count:', count)
chars[j] = ch
j += 1
if count > 1:
for t in str(count):
chars[j] = t
j += 1
for i, ch in enumerate(chars):
if i == 0: continue
if ch != chars[i-1]:
_appendCharCount(chars[i-1], count)
count = 1
else:
count += 1
_appendCharCount(chars[i], count)
del chars[j:]
return len(chars)
# NOTE: compare i with i+1
def compress(self, chars: List[str]) -> int:
j = 0
count = 1
def _appendCharCount(ch, count):
nonlocal j
#print ('_appendCharCount, j:', j, ' i:', i, ' count:', count)
chars[j] = ch
j += 1
if count > 1:
for t in str(count):
chars[j] = t
j += 1
for i, ch in enumerate(chars):
if i == len(chars) -1 or ch != chars[i+1]:
_appendCharCount(ch, count)
count = 1
else:
count += 1
del chars[j:]
return len(chars)