前往此题

计数法

借助两个变量作为辅助,ant表示当前扫描的字符,count表示当前扫描字符的重复数。当扫描到的字符与ant不相等的时候,res变量记作res += ant + str(count),为了节约内存没用使用res = res + ant + str(count)。如果相等则计数count + 1,继续扫描。最后再根据res与S的长度决定返回值。

代码

class Solution:
    def compressString(self, S: str) -> str:
        if not S: return ""
        count = 0
        res = ""
        ch = S[0]

        for s in S:
            if s == ch: count += 1
            else:
                res += ch + str(count)
                count = 1
                ch = s
        res += ch + str(count)
        return res if len(res) < len(S) else S