Duplicate Character Formatting

import java.util.;
public class Main {
public static String DoubleCheck(String s, int n){
if (n==1 || n==0){
return s;
}
for(int i=0; i<n-1; i++){
if(s.charAt(i)==s.charAt(i+1)){
return s.substring(0,i+1) + "
" + s.substring(i+1,n);
}
}
String ans = DoubleCheck(s, n-1);
return ans;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
int n = s.length();
String res = DoubleCheck(s,n);
System.out.println(res);
}
}

I wrote the above code. It is working for cases like “hello”, “john” etc. But it is not working for cases like “sssra”, “aaab” etc. What should I change in my code?

So your code is working only when there is single occurrence of double character like in hello, because of your if code
if(s.charAt(i)==s.charAt(i+1)){
return s.substring(0,i+1) + “” + s.substring(i+1,n);
}
once if find a match like char(i) == char(i+1) , it just returns.

in this case , you don’t need both a loop and recursion. you need to think about it. why?
You can solve this either using loop or recursion, only one of this.
like

import java.util.;
public class Main {
public static String DoubleCheck(String s, int n){
if (n==1 || n==0){
return s;
}
for(int i=0; i<s.length()-1; i++){
if(s.charAt(i)==s.charAt(i+1)){
s = s.substring(0,i+1) + "
" + s.substring(i+1,s.length());
}
}
return s;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
int n = s.length();
String res = DoubleCheck(s,n);
System.out.println(res);
}
}

this is a loop solution. just check if body carefully. try to write recursive version of it by yourself.

Thanks

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.