1209. Remove All Adjacent Duplicates in String II
Question
You are given a string
sand an integerk, akduplicate removal consists of choosingkadjacent and equal letters fromsand removing them, causing the left and the right side of the deleted substring to concatenate together.We repeatedly make
kduplicate removals onsuntil we no longer can.Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.
Solution
用一个栈保存当前的字符,同时建立一个cnt[]数组记录当前字符连续出现的次数。
遍历字符串。
如果当前的字符与栈顶的字符相同时,获取数组中记录的当前连续次数lastCount并加一。
如果lastCount等于k,则匹配到了足够的字符,去掉栈顶的k - 1个元素。
否则将字符串加入栈顶,记录当前位置的出现次数lastCount。
如果当前字符与栈顶字符不同,则将字符直接加入栈顶,记录当前位置的cnt[dq.size()]为1。
最后将栈内元素倒序组成字符串。由于需要这一步操作,因此之前的栈采用双端队列实现。
Code
1 | class Solution { |
