import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
String str = cin.next();
printString(str,"",str);
}
public static void printString(String str,String ans,String org){
if(str.length() == 0){
if(isGreater(ans,org)){
System.out.println(ans);
}
return ;
}
for(int i = 0;i<str.length();i++){
char ch = str.charAt(i);
String ros = str.substring(0 , i)+ str.substring(i+1);
printString(str,ans+ch,org);
}
}
public static boolean isGreater(String ans, String org){
if(ans.length() == 0){
return true;
}
char ch1 = ans.charAt(0), ch2 = org.charAt(0);
if(ch1<ch2){
return false;
}else{
return isGreater(ans.substring(1),org.substring(1));
}
}
}====what’s the error in the code please make corrections and point them
Dictionary oder larger problem
your code is correct but you made mistake in recursive call…
printString(ros,ans+ch,org); //should be ros instead of str
Moreover as you need to print strings strictly larger in dictionary order, you need to handle isGreater() carefully for all three cases. I have correct isGreater()… have a look.
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
String str = cin.next();
printString(str,"",str);
}
public static void printString(String str,String ans,String org){
if(str.length() == 0){
if(isGreater(ans,org)){
System.out.println(ans);
}
return ;
}
for(int i = 0;i<str.length();i++){
char ch = str.charAt(i);
String ros = str.substring(0 , i)+ str.substring(i+1);
printString(ros,ans+ch,org);
}
}
public static boolean isGreater(String ans, String org){
if(ans.length() == 0){
return false;
}
char ch1 = ans.charAt(0), ch2 = org.charAt(0);
if(ch1<ch2){
return false;
}else if(ch1>ch2){
return true;
}
return isGreater(ans.substring(1),org.substring(1));
}
}
Thanks. and don’t forget to rate:)
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.