1#define pp pair<int, char>23class Solution {4public:5string removeDuplicates(string s, int k) {6int n = s.size();78stack<pp> stk;910int i = 0;1112while (i < n) {13int count = 1;1415char ch = s[i];1617while ((i + 1) < n && s[i] == s[i + 1]) {18i++;19count++;20}2122int c = 0;2324if (!stk.empty() && stk.top().second == ch) {25c += stk.top().first;26stk.pop();27}2829count += c;3031count = count % k;3233if (count != 0) {34stk.push({count, ch});35}3637i++;38}3940string str = "";4142while (!stk.empty()) {43int count = stk.top().first;4445while (count--) {46str.push_back(stk.top().second);47}4849stk.pop();50}5152reverse(str.begin(), str.end());5354return str;55}56};