-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathRemove All Adjacent Duplicates in String II.cpp
53 lines (37 loc) · 1.41 KB
/
Remove All Adjacent Duplicates in String II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Solution by Rahul Surana
***********************************************************
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.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
string removeDuplicates(string s, int k) {
int n = s.size();
if(n<k) return s;
stack<pair<char,int>> stk;
for(int i=0; i<n; ++i){
if(stk.empty() || stk.top().first != s[i]) stk.push({s[i],1});
else{
auto prev = stk.top();
stk.pop();
stk.push({s[i], prev.second+1});
}
if(stk.top().second==k) stk.pop();
}
string ans = "";
while(!stk.empty()){
auto cur = stk.top();
stk.pop();
while(cur.second--){
ans.push_back(cur.first);
}
}
reverse(ans.begin(), ans.end());
return ans;
}
};