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;
}
};