-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstr2.py
More file actions
54 lines (44 loc) · 1.37 KB
/
str2.py
File metadata and controls
54 lines (44 loc) · 1.37 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
53
54
class Solution(object):
def compress(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
# Logic 1: 2 pointer method - inplace replacement is the only way you could do this...
select = 0
i = 1
n = len(chars)
length = 1
while i < n:
count = 1
while i < n and chars[i] == chars[select]:
count += 1
i += 1
if count > 1:
count = str(count)
for dig in count:
select += 1
chars[select] = dig
length += 1
if i < n:
select += 1
chars[select] = chars[i]
length += 1
i += 1
return length
# Below logic uses extra space
"""
result = []
while chars:
if not result:
result.append(chars.pop(0))
result.append("1")
else:
if result[-2] == chars[0]:
result[-1] = str(int(result[-1])+1)
else:
result.append(chars[0])
result.append("1")
chars.pop(0)
return len(result)
"""