一道关于字符串压缩的面试题

题目

编写一个算法,实现基本的字符串“压缩”算法,比如对于字符串’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

总结:算法一比较好,可读性更强

    原文作者:waketzheng
    原文地址: https://blog.csdn.net/jaket5219999/article/details/80989546
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞