leetcode 443. String Compression

题目叙述:

Given an array of characters, compress it in-place.

The length after compression must always be smaller than or equal to the original array.

Every element of the array should be a character (not int) of length 1.

After you are done modifying the input array in-place, return the new length of the array.

在这里插入图片描述

class Solution:
    def compress(self, chars: List[str]) -> int:
        if len(chars)==0 or len(chars)==1:
            return len(chars)
        
        now = chars[0]
        count = 1
        countchar = -1
        counter = 0
        for i in range(1,len(chars)):
            if chars[i] == now:
                count+=1
                if (i ==len(chars)-1):
                    countchar+=1
                    chars[countchar] = now 
                    countchar2 = countchar+1
                    if count>1:
                        while(count):
                            counter +=1
                            remain = count%10
                            count = count//10
                            countchar+=1
                            chars[countchar] = str(remain)        
                     #翻转部分列表
                    chars[countchar2:countchar2+counter] = chars[countchar2+counter-1:countchar2 -1:-1]
                    counter=0
                    
            else:
                countchar+=1
                chars[countchar] = now 
                countchar2 = countchar+1
                if count>1:
                    
                    while(count):
                        counter +=1
                        remain = count%10
                        count = count//10
                        countchar+=1
                        chars[countchar] = str(remain)
                    
                #翻转部分列表
                    chars[countchar2:countchar2+counter] = chars[countchar2+counter-1:countchar2 -1:-1]    
                    counter=0
                    
                    
                now = chars[i]
                count = 1
                if i == len(chars)-1:
                    countchar+=1
                    chars[countchar] = now 
        print(chars)
        
        num =  countchar+ 1
        print(num)
        return num
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值