how can i do lexographic sorrtingof the subsequences in this program.please help me with the code
Print subsequences problem
i have printed the subsequences but dont know to sort them.how to do it here.
import java.util.*;
public class Main {
public static void main(String args[]) {
int n;
String str="";
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
sc.nextLine();
for(int i=0;i<n;i++){
str=sc.nextLine();
printss(str," ");
}
}
public static void printss(String str,String result){
if(str.length()==0){
System.out.println(result);
return;
}
char cc=str.charAt(0);
String ros=str.substring(1);
printss(ros,result);
printss(ros,result+cc);
}}
@malhotranaman83,
Instead of printing the result. Add that result to an arraylist and return the arraylist to the main method. After that just sort the arraylist for the final answer and print the sorted arraylist.
I DONT KNOW HOW TO sort the arralist so please modify in the code
import java.util.*;
public class Main {
public static void main(String args[]) {
int n;
String str="";
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
sc.nextLine();
for(int i=0;i<n;i++){
str=sc.nextLine();
Collections.sort(getSS(str));
System.out.print(getSS(str));
}}
public static ArrayList<String> getSS(String str)
{
if(str.length() == 0)
{
ArrayList <String> baseResult = new ArrayList<>();
baseResult.add(" ");
return baseResult;
}
char cc = str.charAt(0);
String ros = str.substring(1);
ArrayList <String> myResult = new ArrayList<>();
ArrayList <String> recResult = getSS(ros);
for(int i = 0 ; i< recResult.size(); i++)
{
myResult.add(recResult.get(i));
myResult.add(cc+recResult.get(i));
}
return myResult;
}
}
Just return the list. For sorting you can use Collections.sort or define your own comparator.