题目:消除字符串中出现的相邻重复字符
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
所以,我们只要按照这个思路,定义两个数组分别用来纪录:依次遇到的不同字符,以及他们连续出现的次数。
在遍历字符串的时候:
- 如果字母列表为空,字母添加到letter_list, 该字符出现次数1添加到count_list。
- 如果当前字母和上一个字母(letter_list[-1])不同,则是新字母,添加到letter_list末尾, 1添加到count_list末尾。
- 如果当前字母和上一个字母(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)