Run
#include <bits/stdc++.h>
using namespace std;
string removeDuplicates(string s, char ch)
{
// Base condition
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;
while (remStr.length() > 0 && s.length() > 0 && remStr[0] == s[s.length() - 1])
{
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 = "aabbaaacdffd";
cout << removeDuplicates(str1, ' ') << endl;
}
// when you try to run string = “acaabbbceddd” this code output is wrong is wrong.
// Maybe the correct code is this :-
#include
using namespace std;
//Function to remove Duplicates
string removeDuplicates(string str){
stackstck;
for(int i=0; i< str.length(); i++){
if(stck.empty() or stck.top()!= str[i])
stck.push(str[i]);
else {
while(str[i]==stck.top()){
i++;
}
i–;
stck.pop();
}
}
if(stck.empty())
return "Empty String";
string result = "";
while(!stck.empty()){
result = stck.top()+result;
stck.pop();
}
return result;
}
//Driver Code
int main(){
string str="acaabbbceddd";
cout<< removeDuplicates(str);
}