What is an elegant way to find all the permutations of a string. E.g. permutation for ba
, would be ba
and ab
, but what about longer st
Let's use input abc
as an example.
Start off with just the last element (c
) in a set (["c"]
), then add the second last element (b
) to its front, end and every possible positions in the middle, making it ["bc", "cb"]
and then in the same manner it will add the next element from the back (a
) to each string in the set making it:
"a" + "bc" = ["abc", "bac", "bca"] and "a" + "cb" = ["acb" ,"cab", "cba"]
Thus entire permutation:
["abc", "bac", "bca","acb" ,"cab", "cba"]
Code:
public class Test
{
static Set permutations;
static Set result = new HashSet();
public static Set permutation(String string) {
permutations = new HashSet();
int n = string.length();
for (int i = n - 1; i >= 0; i--)
{
shuffle(string.charAt(i));
}
return permutations;
}
private static void shuffle(char c) {
if (permutations.size() == 0) {
permutations.add(String.valueOf(c));
} else {
Iterator it = permutations.iterator();
for (int i = 0; i < permutations.size(); i++) {
String temp1;
for (; it.hasNext();) {
temp1 = it.next();
for (int k = 0; k < temp1.length() + 1; k += 1) {
StringBuilder sb = new StringBuilder(temp1);
sb.insert(k, c);
result.add(sb.toString());
}
}
}
permutations = result;
//'result' has to be refreshed so that in next run it doesn't contain stale values.
result = new HashSet();
}
}
public static void main(String[] args) {
Set result = permutation("abc");
System.out.println("\nThere are total of " + result.size() + " permutations:");
Iterator it = result.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}