1209. Remove All Adjacent Duplicates in String II
class Solution {
public:
    string removeDuplicates(string s, int k) {
        stack<pair<char, int>> main;
        for(auto ch : s){
            if(!main.empty() && main.top().first == ch){
                main.top().second++;
            }
            else{
                main.push({ch, 1});
            }
            if(!main.empty() && main.top().second == k){
                main.pop();
            }
        }
        string str;
        while(!main.empty()){
            while(main.top().second--) {
                str += main.top().first;
            }
            main.pop();
        }
        reverse(str.begin(), str.end());
        return str;
    }
};
Comments (0)