Skip to content

Commit c9e1085

Browse files
authored
Create string_compression.py
1 parent d5e635e commit c9e1085

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

string_compression.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
"""
3+
@param str: a string
4+
@return: a compressed string
5+
"""
6+
def compress(self, str):
7+
# write your code here
8+
if not str:
9+
return str
10+
ret = [str[0]]
11+
prev_c = str[0]
12+
count = 1
13+
for i in range(1, len(str)):
14+
if str[i] == prev_c:
15+
count += 1
16+
else:
17+
ret.append('%d' % count)
18+
prev_c = str[i]
19+
ret.append(prev_c)
20+
count = 1
21+
ret.append('%d' % count)
22+
ret = ''.join(ret)
23+
return str if len(ret) >= len(str) else ret
24+
25+
# easy: http://lintcode.com/zh-cn/problem/string-compression/

0 commit comments

Comments
 (0)