public static ArrayList allPermutations(String str) { if (str == null) return null;
ArrayList list = new ArrayList();
if (str.length() == 0) { list.add(""); return list; }
char first = str.charAt(0);
String remaining = str.substring(1);
ArrayList words = allPermutations(remaining); for (String word : words) { for (int i = 0; i <= word.length(); i++) { String s = insertAt(word, i, first);
list.add(s); } } return list; }
private static String insertAt(String s, int index, char ch) { if (index < 0 || index > s.length()) throw new IllegalArgumentException("Index out of bound."); String s1 = s.substring(0, index); String s2 = s.substring(index); return s1 + ch + s2; }
public static ArrayList allPermutations(String str) {
if (str == null)
return null;
ArrayList list = new ArrayList();
if (str.length() == 0) {
list.add("");
return list;
}
char first = str.charAt(0);
String remaining = str.substring(1);
ArrayList words = allPermutations(remaining);
for (String word : words) {
for (int i = 0; i <= word.length(); i++) {
String s = insertAt(word, i, first);
list.add(s);
}
}
return list;
}
private static String insertAt(String s, int index, char ch) {
if (index < 0 || index > s.length())
throw new IllegalArgumentException("Index out of bound.");
String s1 = s.substring(0, index);
String s2 = s.substring(index);
return s1 + ch + s2;
}