题目
编写一个算法,实现基本的字符串“压缩”算法,比如对于字符串’abbbbffcccdddcc’,经过算法处理之后得到的输出为’a1b4f2c3d3c2’,如果处理后的字符串长度不小于原串长度,则返回原串。
算法
算法一
In [38]: def compress(s):
...: ss = [s[0], 1]
...: for c in s[1:]:
...: if ss[-2] != c:
...: ss.extend([c, 1])
...: else:
...: ss[-1] += 1
...: return ''.join(str(i) for i in ss) if len(ss) < len(s) else s
...:
...:
In [39]: compress('abbbbffcccdddcc') == 'a1b4f2c3d3c2'
Out[39]: True
算法二
In [36]: def compress(s):
...: ks = [0] + [i for i in range(1, len(s)) if s[i]!=s[i-1]]
...: ss = [f'{s[ks[i]]}{ks[i+1]-ks[i]}' for i in range(len(ks)-1)]+[f'{s[-1]}{len(s)-ks[-1]}']
...: return ''.join(ss) if len(ss) < len(s) else s
...:
...:
In [37]: compress('abbbbffcccdddcc') == 'a1b4f2c3d3c2'
Out[37]: True
总结:算法一比较好,可读性更强