LeetCode-Python0-443. 压缩字符串(字符串)

给你一个字符数组 chars ,请使用下述算法压缩:

从一个空字符串 s 开始。对于 chars 中的每组 连续重复字符 :

  • 如果这一组长度为 1 ,则将字符追加到 s 中。
  • 否则,需要向 s 追加字符,后跟这一组的长度。

压缩后得到的字符串 s 不应该直接返回 ,需要转储到字符数组 chars 中。需要注意的是,如果组长度为 10 或 10 以上,则在 chars 数组中会被拆分为多个字符。

请在 修改完输入数组后 ,返回该数组的新长度。

你必须设计并实现一个只使用常量额外空间的算法来解决此问题。

示例 1:

输入:chars = ["a","a","b","b","c","c","c"]
输出:返回 6 ,输入数组的前 6 个字符应该是:["a","2","b","2","c","3"]
解释:"aa" 被 "a2" 替代。"bb" 被 "b2" 替代。"ccc" 被 "c3" 替代。

示例 2:

输入:chars = ["a"]
输出:返回 1 ,输入数组的前 1 个字符应该是:["a"]
解释:唯一的组是“a”,它保持未压缩,因为它是一个字符。

示例 3:

输入:chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
输出:返回 4 ,输入数组的前 4 个字符应该是:["a","b","1","2"]。
解释:由于字符 "a" 不重复,所以不会被压缩。"bbbbbbbbbbbb" 被 “b12” 替代。

提示:

  • 1 <= chars.length <= 2000
  • chars[i] 可以是小写英文字母、大写英文字母、数字或符号

思路:

利用双指针的办法,我们用 i 和 j 找到每一段连续相同的字符,

然后根据这个相同字符串的长度,如果大于 1,就要写入数字,如果是1,只放字符就够了。

时间复杂度:O(N)因为每个字符只被访问了一次

空间复杂度:O(logN),因为输入最长为 2000,那么最多有连续2000个相同的数字,在用 str() 进行转化为字符串的时候会产生 4 位 的额外空间,即2000跟 10 的对数。这里可以通过 短除法得到每一位的值,再写入数组,最后再原地翻转排序,这样的空间复杂度就是 O(1)

class Solution:
    def compress(self, chars: List[str]) -> int:
        res = 0
        index = 0
        i = 0
        while i < len(chars):
            char, j = chars[i], i
            while j < len(chars) and chars[j] == char:
                j += 1
            same_letter_count = j - i
            chars[index] = char
            index += 1
            if same_letter_count == 1:
                res += 1 
            else:
                res += 1 + len(str(same_letter_count))
                for digit in str(same_letter_count):
                    chars[index] = digit
                    index += 1
            i = j
        return res

第二种思路:

实现一下 O(1)额外空间:

class Solution:
    def compress(self, chars: List[str]) -> int:
        def reverse(left, right):
            while left < right:
                chars[left], chars[right] = chars[right], chars[left]
                left += 1
                right -= 1
            
        res = 0
        index = 0
        i = 0
        while i < len(chars):
            char, j = chars[i], i
            while j < len(chars) and chars[j] == char:
                j += 1
            same_letter_count = j - i
            chars[index] = char
            index += 1
            if same_letter_count == 1:
                res += 1 
            else:
                res += 1 + len(str(same_letter_count))
                left = index
                while same_letter_count:
                    same_letter_count, digit = divmod(same_letter_count, 10)
                    chars[index] = str(digit)
                    index += 1
                reverse(left, res - 1)
            i = j
        return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值