LeetCode 面试01.06 字符串压缩

字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
示例1:
输入:“aabcccccaaa”
输出:“a2b1c5a3”
示例2:
输入:“abbccd”
输出:“abbccd”
解释:“abbccd"压缩后为"a1b2c2d1”,比原字符串长度更长。

解法:双指针(Python)

在这里插入图片描述

class Solution:
    def compressString(self, S: str) -> str:
        res = ""
        i = 0
        while i < len(S):
            j = i 
            while j < len(S) and S[i] == S[j]:
                j += 1
            res += S[i] + str(j - i)
            i = j
        return res if len(res) < len(S) else S
发布了152 篇原创文章 · 获赞 22 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_38204302/article/details/104899931