首页 > 试题广场 >

压缩字符串(一)

[编程题]压缩字符串(一)
  • 热度指数:7059 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2bc5a3。
1.如果只有一个字符,1不用写
2.字符串中只包含大小写英文字母(a至z)。

数据范围:
0<=字符串长度<=50000

要求:时间复杂度O(N)
示例1

输入

"aabcccccaaa"

输出

"a2bc5a3"
示例2

输入

"shopeew"

输出

"shope2w"
class Solution:
    def compressString(self , param ):
        # write code here
        if not param:
            return ""
        cnt = 1
        tmp = param[0]
        res = tmp
        for i, v in enumerate(param[1:]):
            if v == tmp:
                cnt += 1
            elif v != tmp:
                if cnt > 1:
                    res += str(cnt)
                res += v
                tmp = v
                cnt = 1
        if cnt > 1:
            res += str(cnt)
        return res

发表于 2022-07-07 22:49:20 回复(0)
class Solution:
    def compressString(self , param ):
        # write code here
        if len(param) <= 1: return param
        res = []
        count = 0
        n = len(param)
        for i in range(n):   
            count += 1
            if i==n-1&nbs***bsp;param[i] != param[i+1]:
                # 记录字母和次数
                res.append(param[i])
                if count > 1:
                    res.append(str(count))
                count = 0

        return ''.join(res)

发表于 2022-04-19 16:46:18 回复(0)
class Solution:
    def compressString(self , param ):
        # write code here
        a = param
        b = []
        if(param != ""):
            temp = [a[0],1]
            for i in range(1,len(a)):
                if(a[i] == temp[0]):
                    temp[1] += 1
                else:
                    b.append(temp)
                    temp = [a[i],1]
            b.append(temp)
        result = ""
        for i in b:
            if(i[1] == 1):
                #print(i[0],end="")
                result += i[0]
            else:
                #print("%s%d"%(i[0],i[1]),end="")
                result += "%s%d"%(i[0],i[1])
        return result

发表于 2022-01-18 14:52:00 回复(0)
class Solution:
    def compressString(self , param ):
        # write code here
        if len(param)==1&nbs***bsp;0&nbs***bsp;not param:
            return param
        res=[]
        i,v=0,1
        while i <=len(param)-1:
            while i <len(param)-1 and param[i]==param[i+1]:
                v+=1
                i+=1
            while i <len(param)-1 and param[i]!=param[i+1]&nbs***bsp;i ==len(param)-1:
                res.append(param[i])
                res.append(v)
                v=1
                i+=1
        return "".join(map(str, [x for x in res if x != 1]))

发表于 2022-01-11 08:56:34 回复(0)