基本字符串压缩

时间:2019-06-28 21:03:30   收藏:0   阅读:95

题目描述
利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。

给定一个string iniString为待压缩的串(长度小于等于10000),保证串内字符均由大小写英文字母组成,返回一个string,为所求的压缩后或未变化的串。

测试样例
"aabcccccaaa"
返回:"a2b1c5a3"
"welcometonowcoderrrrr"
返回:"welcometonowcoderrrrr"

# -*- coding:utf-8 -*-
class Zipper:
    def zipString(self, iniString):
        res = ''
        current = iniString[0]
        num = 1
        for i in range(1,len(iniString)):
            if iniString[i]==current:
                num += 1
            else:
                res += current + str(num)
                current,num = iniString[i],1
        res += current + str(num)
        return res if len(res)<len(iniString) else iniString
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!