Leetcode 443. String Compression

142 篇文章 0 订阅
121 篇文章 0 订阅

Problem

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

  • If the group’s length is 1, append the character to s.
  • Otherwise, append the character followed by the group’s length.

The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

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

You must write an algorithm that uses only constant extra space.

Algorithm

Count each character and save the number, if the number bigger than one.

Code

class Solution:
    def compress(self, chars: List[str]) -> int:
        if not chars:
            return None
        
        ch, cnts, slen, index = chars[0], 1, len(chars), 0
        for i in range(1, slen):
            if chars[i] == ch:
                cnts += 1
            else:
                chars[index] = ch
                index += 1
                if cnts > 1:
                    for digit in str(cnts):
                        chars[index] = digit
                        index += 1
                ch = chars[i]
                cnts = 1
        
        chars[index] = ch
        index += 1
        if cnts > 1:
            for digit in str(cnts):
                chars[index] = digit
                index += 1
        
        return index
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值