Question - Given a string s, remove all its adjacent duplicate characters recursively.
MY CODE:
string remove(string s){
if(s . size() == 0){
return s ;
}
string ans ;
int j = 0, count = 1 ;
for(j = 0 ; j <= (s . size()-2) ; j++){
if(s[j] == s[j+1]){
count++ ;
}
else{
if(count == 1){
ans.push_back(s[j]) ;
}
else{
count = 1 ;
}
}
}
if(count == 1){
ans.push_back(s[j]) ;
}
if(s.size() == ans.size()){
return ans ;
}
return remove(ans) ;
}
This code works fine for all the inputs except for the input with size 1, if I replace j<=s.size()-2
with j< s.size()-1
, it works fine for input with size 1 too. I am not able to figure out what's wrong with the above code why its showing runtime error with the above code.