Friday, March 24, 2017

Generate All Permutations of a String

Suppose we are given a String and asked to find all the permutations of that String.

So for abcd it will be like:

bdAc
bdcA
cAbd
cAdb
cbAd
cbdA
cdAb
cdbA
dAbc
dAcb
dbAc
dbcA
dcAb

dcbA

The Java code should be the following:

public class StringPermutation {
    
    public static void main(String args[]){
        String perm = "Abcd";
        System.out.println(permutation("",perm));
    }
    public static String permutation(String prefix, String perm){
        if(perm.length() == 0){
            System.out.println(prefix);
 } else{
               for (int i = 0; i < perm.length(); i++){
                   permutation(prefix + perm.charAt(i), perm.substring(0,i
                      + perm.substring(i+1));
               }
}
        return prefix;
    }

}

No comments:

Post a Comment