题目
编写一个算法,实现基本的字符串“压缩”算法,比如对于字符串'abbbbffcccdddcc',经过算法处理之后得到的输出为'a1b4f2c3d3c2',如果处理后的字符串长度不小于原串长度,则返回原串。
算法
算法一
def str_compress(string):
result = []
current = string[0]
count = 1
for s in string[1:]:
if s == current:
count += 1
else:
# result += current + str(count)
result.append(current)
result.append(str(count))
current = s
count = 1
# result += current + str(count)
result.append(current)
result.append(str(count))
# return result
return ''.join(result)
s = 'abbbbffcccdddcc'
print(str_compress(s))
a1b4f2c3d3c2
算法二
# 使用itertools模块的groupby方法
from itertools import groupby
def str_compress2(string):
result = []
for key, group in groupby(string):
result.append(key)
result.append(str(len(list(group))))
return ''.join(result)
s = 'abbbbffcccdddcc'
print(str_compress2(s))
a1b4f2c3d3c2