编写一个算法,实现基本的字符串“压缩”算法,比如对于字符串abbbbbccccdddcccccc,经过算法处理之后得到的输出为a1b5c4d3c6,如果处理后的字符串长度不小于原串长度,则返回原串。
def compress_str(string):
result = []
count = 1
current = string[0]
for ch in string[1:]:
if ch == current:
count += 1
else:
result.append(current)
result.append(str(count))
count = 1
current = ch
result.append(current)
result.append(str(count))
if len(result) >= len(string):
return string
return ''.join(result)