although the code i wrote passed all test cases but i think there could be a better approach. Please take a look at my solution.
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner s1=new Scanner(System.in);
String str=s1.next();
String ans=repeatchar(str,"");
System.out.print(ans);
}
public static String repeatchar(String str,String ans){
if(str.length()==1) {
if(!(str.charAt(0)==ans.charAt(ans.length()-1))) {
ans+=str.charAt(0);
}
return ans;
}
String ch=str.substring(1);
if(!(str.charAt(0)==str.charAt(1))) {
ans+=str.charAt(0);
}
return repeatchar(ch,ans);
}
}
Removing duplicate characters
Your code is perfectly fine. The time complexity is O(n) which is the optimized approach.