Remove All Adjacent Duplicates in String II in C++


Suppose a string s is given, a k duplicate removal consists of choosing k adjacent and equal letters from string s and removing them causing the left and the right side of the deleted substring to concatenate together. We will repeatedly make k duplicate removals on the given string s until we cannot change any remaining. We have to find the final string after all such duplicate removals have been made. So if the input is like s = “deeedbbcccbdaa”, and k = 3, then the output will be “aa”, at first delete the “eee” and “ccc” and we will get “ddbbbaa”, then delete “bbb”, the string will be “dddaa”, then delete “ddd”, and the output will be “aa”

To solve this, we will follow these steps −

  • ans := empty string
  • create one stack for char-int pair, n := size of the string
  • for i in range 0 to n
    • x := s[i]
    • if stack is not empty and integer of the stack top element = k, then delete top element from stack
    • if i = n, then break
    • if stack is empty or character of stack top is not x, then insert pair (x, 1) into stack, and increase i by 1
    • otherwise increase the integer part of the stack top element, and increase i by 1
  • while stack is not empty
    • temp := stack top element
    • while integer part of temp is not 0,
      • ans := ans + character part of temp
      • decrease integer part of temp by 1
    • delete the top element from stack
  • reverse the ans string and return.

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string removeDuplicates(string s, int k) {
      string ans = "";
      stack < pair<char, int> > st;
      int n = s.size();
      for(int i = 0; i <= n;){
         char x = s[i];
         if(!st.empty() && st.top().second == k)st.pop();
         if(i == n)break;
         if(st.empty() || st.top().first != x){
            st.push({x, 1});
            i++;
         } else {
            st.top().second++;
            i++;
         }
      }
      while(!st.empty()){
         pair <char, int> temp = st.top();
         while(temp.second--) ans += temp.first;
         st.pop();
      }
      reverse(ans.begin(), ans.end());
      return ans;
   }
};
main(){
   Solution ob;
   cout <<(ob.removeDuplicates("deeedbbcccbdaa", 3));
}

Input

"deeedbbcccbdaa"
3

Output

aa

Updated on: 30-Apr-2020

561 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements