Print all permutations of String

Print all permutations of String

Example:

Input:  str="Java"
Output: All the permutations: 
Java, Jaav, Jvaa, Jvaa, Java, Jaav, aJva, aJav, avJa, avaJ, aavJ, aaJv, vaJa, vaaJ, vJaa, vJaa, vaJa, vaaJ, aavJ, aaJv, avaJ, avJa, aJva, aJav, 

Approach

Java

public class PermuteStringGen {

    public static void main(String[] args) {
        String str = "Java";
        int len = str.length();
        System.out.println("All the permutations: ");
        genPermutationS(str, 0, len);
    }

    // Method to generate all permutations
    public static void genPermutationS(String strint startint end) {
        // Prints the permutations
        if (start == end - 1)
            System.out.print(str + ", ");
        else {
            for (int i = start; i < end; i++) {
                // Swapping the string by fixing a character
                str = strSwap(str, start, i);
                // Recursively calling
                genPermutationS(str, start + 1, end);
                // Backtracking and swapping the characters again.
                str = strSwap(str, start, i);
            }
        }
    }
    // Swap
    public static String strSwap(String aint iint j) {
        char[] b = a.toCharArray();
        char ch;
        ch = b[i];
        b[i] = b[j];
        b[j] = ch;
        return String.valueOf(b);
    }

}


No comments:

Post a Comment