1209.Remove All Adjacent Duplicates in String II 简单解法

题目:消除字符串中出现的相邻重复字符

Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made.

It is guaranteed that the answer is unique.

因为这题难度是Medium, 所以一开始我也把它想复杂了。以此考虑了栈、OrderedDict,深究一下都不行。突然想到了N年前做过的一道面试题,字符串压缩:


把字符串压缩成字母及其连续出现次数的形式, 例如:

abcd --> a1b1c1d1

abbbccdc --> a1b3c2d1c1

所以,我们只要按照这个思路,定义两个数组分别用来纪录:依次遇到的不同字符,以及他们连续出现的次数。
在遍历字符串的时候:

  1. 如果字母列表为空,字母添加到letter_list, 该字符出现次数1添加到count_list。
  2. 如果当前字母和上一个字母(letter_list[-1])不同,则是新字母,添加到letter_list末尾, 1添加到count_list末尾。
  3. 如果当前字母和上一个字母(letter_list[-1])相同,该字母相邻重重次数加1, letter_list[-1]++。
    如果letter_list[-1]==k;如果相邻的相同字母满足消除条件,消除该字母,即:从两个列表里面分别消除该字母及其出现的次数。

最后,得到根据两个列表剩余值,合成字符串。代码如下:

class Solution(object):
    def removeDuplicates(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        #store letter and count
        char_list = []
        count_list = []
        for ch in s:
            #first letter or all previous letters are removed
            if len(char_list) == 0:
                char_list.append(ch)
                count_list.append(1)
                continue
            #current letter is not as same as last
            if ch != char_list[-1]:
                char_list.append(ch)
                count_list.append(1)
            else: # ch == char_list[-1]
                #if current letter same with last, times plus one
                count_list[-1] += 1
                #if current letter k duplicate, remove it
                if count_list[-1] == k:
                    char_list.pop()
                    count_list.pop()
        res = []
        for i in range(len(char_list)):
            ch = char_list[i]
            cnt = count_list[i]
            res.extend([ch]*cnt)
        if len(res) == 0:
            return ''
        else:
            return ''.join(res)
                       
                
        
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值