Strings-Remove Duplicates

import java.util.*;
public class Main{
public static String remove(String str,char last_rem){
if (str.length() == 0 || str.length() == 1)
return str;
if (str.charAt(0) == str.charAt(1))
{
last_rem=str.charAt(0);
if(str.length()>1 && str.charAt(0) == str.charAt(1))
str=str.substring(1,str.length());
str=str.substring(1,str.length());
return remove(str,last_rem);}
String rem_str=remove(str.substring(1,str.length()),last_rem);
if (rem_str.length() != 0 && rem_str.charAt(0) == str.charAt(0)) {
last_rem=str.charAt(0);
return rem_str.substring(1,rem_str.length());}

if (rem_str.length() == 0 && last_rem == str.charAt(0))
return rem_str;
return (str.charAt(0) + rem_str);
}

  static String removeA(String str)   
  { 
         char last_removed = '\0'; 
         return remove(str, last_removed); }

public static void main(String args[]){
try{
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
String res=removeA(str);
System.out.println(res);
}
catch(Exception e){System.out.println(e);}}
}

Hi @Sweta,
Your code is majorly wrong . It does not work even for basic cases … For example it won’t run for testcase ‘aaaaaaaa’ . Please correct the code according to this testcase and i hope then it will pass all the test cases . However i would also suggest to use iterative approach as this question is quite basic and using recursion only makes it harder to think.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.