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
Here is a straightforward minimalist recursive solution in Java:
public static ArrayList permutations(String s) {
ArrayList out = new ArrayList();
if (s.length() == 1) {
out.add(s);
return out;
}
char first = s.charAt(0);
String rest = s.substring(1);
for (String permutation : permutations(rest)) {
out.addAll(insertAtAllPositions(first, permutation));
}
return out;
}
public static ArrayList insertAtAllPositions(char ch, String s) {
ArrayList out = new ArrayList();
for (int i = 0; i <= s.length(); ++i) {
String inserted = s.substring(0, i) + ch + s.substring(i);
out.add(inserted);
}
return out;
}