leetcode 面试题 01.06. 字符串压缩

思路

遍历字符串,同时在前后字符串不同时停止计数,

class Solution(object):
    def compressString(self, S):
        """
        :type S: str
        :rtype: str
        """
        if not S:
            return ''
        res = []
        count = 1
        for i in range(1,len(S)):
            if S[i]==S[i-1]:
                count += 1
            else:
                res.append(S[i-1])
                res.append(str(count))
                count = 1
        res.append(S[len(S)-1])
        res.append(str(count))
        result_final = ''.join(res)
        if len(S)<=len(result_final):
            return S
        else:
            return result_final

 

posted @ 2021-09-26 16:38  A-inspire  Views(44)  Comments(0Edit  收藏  举报