1209. Remove All Adjacent Duplicates in String II
[Medium] 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
个相邻且相等的字母,并删除它们,使被删去的字符串的左侧和右侧连在一起。你需要对 s
重复进行无限次这样的删除操作,直到无法继续为止。在执行完所有删除操作后,返回最终得到的字符串。
思路:双指针。同LeetCode1047. 删除字符串中的所有相邻重复项。
class Solution {
public:
string removeDuplicates(string s, int k) {
int i = 0, n = s.size();
vector<int> cnt(n);
for (int j = 0; j < n; ++j, ++i) {
s[i] = s[j];
cnt[i] = (i > 0 && s[i-1] == s[j]) ? cnt[i-1] + 1 : 1;
if (cnt[i] == k)
i = i - k;
}
return s.substr(0, i);
}
};
思路2:栈。栈中的每个元素是{已经出现的次数,对应的字符}。参考lee215。
class Solution {
public:
string removeDuplicates(string s, int k) {
vector<pair<int, char>> sk = {{0, '#'}};
for(auto c : s){
if(sk.back().second != c)
sk.push_back({1, c});
else if(++sk.back().first == k)
sk.pop_back();
}
string res;
for(auto p : sk){
res += string(p.first, p.second);
}
return res;
}
};