-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompress_string.py
47 lines (29 loc) · 936 Bytes
/
compress_string.py
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
'''
Given a string lowercase alphabet s, eliminate consecutive duplicate characters from the string and return it.
That is, if a list contains repeated characters, they should be replaced with a single copy of the character. The order of the elements should not be changed.
'''
from itertools import groupby
class Solution:
def solve(self, s):
res = [ c for c, g in groupby(s)]
print(res)
res = ''.join(res)
print(res)
return res
#another
class Solution:
def solve(self, s):
l = [s[0]]
for c in s[1:]:
if c == l[-1]:
continue
else:
l.append(c)
return "".join(l)
#another
class Solution:
def solve(self, s):
if not s:
return ""
res = [s[0]] + [s[i] for i in range(1, len(s)) if s[i] != s[i - 1]]
return "".join(res)