Find Permutations of a string

 Example ABC -> [ABC, ACB, BAC, BCA, CBA, CAB]




public class FindPermutations {

    // COmplexity
    // O(TIme to find one permutation * Number of permutations)
    // O(n*n!)
    public static void main(String args[]) {
        permutate("abc", 0, 2);
    }

    public static void permutate(String s, int low, int high) {
        if (low == high) {
            System.out.println(s);
            return;
        }

        for (int i = low; i <= high; i++) {
            s = swap(s, low, i);
            permutate(s, low + 1, high);
            s = swap(s, low, i); //Back track to the previous string to get other permutations.Just similar of first step
        }
    }

    private static String swap(String s, int index1, int index2) {
        char[] charArray = s.toCharArray();
        char char1 = charArray[index1];

        charArray[index1] = charArray[index2];
        charArray[index2] = char1;

        return new String(charArray);
    }
}




Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

How to prevent Singleton Class from Reflection and Serialization

Optional Vs Null Check