Find all possible combinations for a given string

Again, this was another interview question that was asked when I had applied for Automation QA engineer role in one of the IT companies in Bangalore.
The question is to write a program to find all possible combinations for a given string Ex: abcdef

package com.packt;

 public class Combi {

    private StringBuilder output = new StringBuilder();
    private final String istring;
    public Combi( final String str ){
        istring = str;
        System.out.println("The input string is: " + istring);
    }
    
    
  public static void main (String args[])
    {
        Combi combi= new Combi("abcdef"); //input string
        System.out.println("Possible combinations for the given string are: ");
        combi.combine();
    }
    
    public void combine() { combine( 0 ); }
    private void combine(int start ){
        for( int i = start; i < istring.length(); ++i ){
            output.append( istring.charAt(i) );
            System.out.println( output );
            if ( i < istring.length() )
            combine( i + 1);
            output.setLength( output.length() - 1 );
        }
    }
}

Here are other ways of doing the same: StackOverFlow

No comments:

Post a Comment