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
Post a Comment