Leetcode 1209. Remove All Adjacent Duplicates in String II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Remove All Adjacent Duplicates in String II

2. Solution

**解析:**Version 1,使用数据结构栈来解决这个问题,时间复杂度O(N)。字符每次入栈之前都与栈顶元素进行比较,如果不同,则入栈元组,元组元素为当前字符以及字符个数1,如果字符相同且栈顶相同字符个数不等于k-1,也入栈元组,元组元素为当前字符以及连续相同字符个数,值为栈顶字符的个数加1,否则,移除栈顶的k-1个字符。

  • Version 1
class Solution:
    def removeDuplicates(self, s: str, k: int) -> str:
        res = []
        for ch in s:
            if not res or res[-1][0] != ch:
                res.append((ch, 1))
            else:
                if res[-1][1] == k -1:
                    del res[-k+1:]
                else:
                    res.append((ch, res[-1][1] + 1))
        res = [x[0] for x in res]
        return ''.join(res)

**解析:**另一种使用栈的方式,当前字符与栈顶字符相同时,只更新栈顶字符的个数。

  • Version 2
class Solution:
    def removeDuplicates(self, s: str, k: int) -> str:
        res = []
        for ch in s:
            if not res or res[-1][0] != ch:
                res.append([ch, 1])
            else:
                if res[-1][1] == k -1:
                    res.pop()
                else:
                    res[-1][1] += 1
        res = [x[0] * x[1] for x in res]
        return ''.join(res)

Reference

  1. https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值