字符串“压缩”

来源:互联网 发布:linux ssh 翻墙 编辑:程序博客网 时间:2024/05/21 08:54

编写一个算法,实现基本的字符串“压缩”算法,比如对于字符串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)
0 0
原创粉丝点击