首页 > 试题广场 >

字符串压缩功能

[编程题]字符串压缩功能
  • 热度指数:1136 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
利用字符重复出现的次数,实现字符串压缩功能。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)
示例1

输入

"abcccaaaa"

输出

"a1b1c3a4"
class Solution:
    def compressString(self , test_string ):
        def compressString(selfSstr) -> str:
            if len(S) == 0:
                return ''
            else:
                a=S[0]
                b=S[0]
                c = 1
                for i in S[1:]:
                    if i == a:
                        c += 1    
                    else:
                        b += str(c)
                        b += i 
                        c = 1
                        a = i
                b += str(c)        
                if len(b) < len(S):
                    return b
                else:
                    return S 
    
发表于 2022-11-10 16:55:37 回复(0)
class Solution:
    def compressString(self , test_string ):
        # write code here滑动窗口:
        left = right = 0
        res = ''
        while right < len(test_string):
            if test_string[right] == test_string[left]:
                right +=1
            else:
                res += test_string[left] + str(right - left)
                left = right
        res += test_string[left] + str(right - left)
        return res if len(res) < len(test_string) else test_string
发表于 2022-09-08 03:17:17 回复(0)
a
class Solution:
    def compressString(self , test_string ):
        left, right = 0,0
        strCount = []
        while right < len(test_string):
            if test_string[right] == test_string[left]:
                right +=1
            else:
                strCount.append([test_string[left], right-left])
                left = right
        strCount.append([test_string[left], right - left])
        print(strCount)
        res = ""
        if len(strCount)*2 >= len(test_string):
            res = test_string
        else:
            for c in strCount:
                res += c[0]+str(c[1])
        print(res)
        return res


编辑于 2021-09-04 16:17:33 回复(0)