You are given a string s and an integer k, 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”
把所有相同的连续k个字符都去掉,去掉后剩下的拼在一起。
拼在一起后连续相同的k个继续去掉,直到没有相同的连续k个字符为止。
思路:
栈和计数。
用当前数组模拟栈,栈顶记为top。
top指向的字符记录它出现了多少次,
一旦满足出现了k次,把栈顶的k个元素都移出,top移到这k个元素之前。
否则压字符入栈。
最后输出栈中的字符。
public String removeDuplicates(String s, int k) {
int n = s.length();
char[] str = s.toCharArray();
int[] cnt = new int[n];
int top = -1;
for(int i = 0; i < n; i++) {
if(top < 0) {
top ++;
str[top] = str[i];
cnt[top] = 1;
} else {
if(str[top] == str[i] && cnt[top] + 1 == k) {
top -= k - 1; //移到k个元素之前,top还没到k(cnt[top]+1),所以是k-1
} else {
top ++; //即将压入栈的下一元素
cnt[top] = str[top - 1] == str[i] ? cnt[top - 1] + 1 : 1; //记入压入栈字符的计数
str[top] = str[i]; //新的字符压入栈
}
}
}
return new String(str, 0, top + 1);
}