Saturday, March 29, 2014

Java Program to find all combinations of a string

To find All combinations of a string is another commonly asked Interview question.

Below is my code for finding all the combinations of a given string with explanation:

public class AllStringCombinations { 
// taking String Builder object as we need to modify many time
     private StringBuilder outputString = new StringBuilder(); 
 
    private final String inputString; 
 
     /*
     *Constructor 
     */

    public AllStringCombinations( final String str ){
        inputString = str;
        System.out.println("The input string  is  : " + inputString);
    }    
    
    public static void main (String args[])
    {
        AllStringCombinations allStringCombinations =
                                    new AllStringCombinations("wxyz"); 
System.out.println("");
        System.out.println("All possible combinations are :  ");
        System.out.println("");
        allStringCombinations.getCombination(0);
    } 
     /*
      *Method to print all possible combinations recursively
      */ 

     public void getCombination(int start) { 
      
     for( int i = start; i <= inputString.length()-1; ++i ){
            outputString.append( inputString.charAt(i) );
            System.out.println( outputString );
            if ( i <= inputString.length() ) 

            // Recursive call

            getCombination( i + 1);
            outputString.setLength( outputString.length() - 1 );
        }
    }
}
 
OUTPUT:
===========================================================================
The input string  is  : wxyz

All possible combinations are :  

w
wx
wxy
wxyz
wxz
wy
wyz
wz
x
xy
xyz
xz
y
yz
z

No comments :

Post a Comment