Remove All Adjacent Duplicates in String II (M)
题目
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.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s
only contains lower case English letters.
题意
给定一个字符串s和整数k,遍历s,如果遇到k个连续字符都相同,则删去这k个字符,并得到新字符串t,对t进行同样的操作,直到最后无字符可删。返回最终得到的字符串。
思路
维护两个栈,分别保存字符和其对应的连续的次数。遍历字符串,如果当前字符与前一个不同,将前一个字符和对应次数压栈;如果当前字符与前一个相同,连续次数累加。然后判断连续次数是否已达到k,如果是则出栈前一个字符和对应次数(相当于将当前字符抛弃)。注意遍历到最后一个字符串时要进行特殊处理。
代码实现
Java
class Solution {
public String removeDuplicates(String s, int k) {
Deque<Character> chars = new ArrayDeque<>();
Deque<Integer> cnts = new ArrayDeque<>();
int cnt = 0;
Character pre = null;
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (pre == null) {
pre = cur;
cnt = 1;
} else if (cur == pre) {
cnt++;
}else {
chars.push(pre);
cnts.push(cnt);
pre = cur;
cnt = 1;
}
if (i == s.length() - 1 && cnt < k) {
chars.push(pre);
cnts.push(cnt);
} else if (i < s.length() - 1 && cnt == k) {
pre = chars.isEmpty() ? null : chars.pop();
cnt = cnts.isEmpty() ? 0 : cnts.pop();
}
}
StringBuilder sb = new StringBuilder();
while (!chars.isEmpty()) {
sb.append((chars.removeLast() + "").repeat(cnts.removeLast()));
}
return sb.toString();
}
}