Recursively remove all adjacent duplicates in C++

Remove all adjacent duplicates

Today we will learn about how to remove all adjacent duplicates in a string.Given a string, recursively remove adjacent duplicate characters from the string. The output string should not have any adjacent duplicates. See the following examples.

Print The First n strong Numbers in C

The goal here is to see if the repeated character in the String remStr matches the last character in the parent String. If this is the case, we must continue to remove that character before concatenating string s and string remStr.

Input: azxxxzy 
Output: ay 
First “azxxxzy” is reduced to “azzy”. 
The string “azzy” contains duplicates, 
so it is further reduced to “ay”.

Recursively remove all adjacent duplicates C++ Code

Run
#include <bits/stdc++.h>
using namespace std;

string removeDuplicates (string s, char ch) 
{

  // If length of string is 1 or 0
  if (s.length () <= 1) 
  {
   return s;
  }

  int i = 0;
  while (i < s.length ())
  {
   if (i + 1 < s.length () && s[i] == s[i + 1])
   {
   int j = i;
   while (j + 1 < s.length () && s[j] == s[j + 1])
   {
    j++;
   }
  char lastChar = i > 0 ? s[i - 1] : ch;

  string remStr = removeDuplicates (
  s.substr (j + 1, s.length ()), lastChar);
  s = s.substr (0, i);

  int k = s.length (), l = 0;
  // Recursively remove all the adjacent
  // characters formed by removing the adjacent characters
  
while (remStr.length () > 0 && s.length () > 0 &&remStr[0] == s[s.length () - 1])
{
  // Have to check whether this is the repeated character that matches the
  // last char of the parent String
  while (remStr.length () > 0 &&remStr[0] != ch &&remStr[0] == s[s.length () - 1])
  {
  remStr = remStr.substr (1, remStr.length ());
  }
  s = s.substr (0, s.length () - 1);
 } 
  s = s + remStr;
  i = j;
 } 
 else
  {
   i++;
   }
  }
 return s;
}
  // Driver Code
 int main () 
 {
 string str1 = "ABBBCDERRR";
 cout << removeDuplicates (str1, ' ') << endl;
 }
ACDE