leetcode 面试题01.06. 字符串压缩 python

leetcode 01.06. 字符串压缩

题目描述

题目描述

解法

这道题很简单,就是计数
有两个地方要注意:

  1. 遇到新的字符后,count记得置回1
  2. 因为是遇到新的不同的字符后才会触发结束计数,添加到新字符串的操作。所以计算到最后一个字符时,不会触发添加才做,计完数了就直接退出for循环,因此在for循环外面再添加一次 添加 操作。
class Solution:
    def compressString(self, S: str) -> str:
        if not S:
            return ''
        newstr = []
        tmp = S[0]
        count = 0
        for i in S:
            if i == tmp:
                count += 1
            else:
                newstr.append(tmp)
                newstr.append(str(count))
                tmp = i
                count = 1
        newstr.append(tmp)
        newstr.append(str(count))
        newstr = ''.join(newstr)
        if len(newstr)>=len(S):
            return S
        else:
            return newstr
发布了28 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/xxx_gt/article/details/104903560