Skip to content

Instantly share code, notes, and snippets.

@ElderMael
Created October 8, 2014 14:37
Show Gist options
  • Save ElderMael/12b9d2cc9ac653c2ab9d to your computer and use it in GitHub Desktop.
Save ElderMael/12b9d2cc9ac653c2ab9d to your computer and use it in GitHub Desktop.
Permutations of a String in Java
static class Permutations {
public static void main(String... args) {
System.out.println("Permutations of 'abcd'");
System.out.println(Permutations.of("abcd"));
}
public static List<String> of(String string) {
if (string == null) {
throw new IllegalArgumentException("string cannot be null.");
}
List<String> permutations = new LinkedList<String>();
if (string.length() == 0) {
permutations.add("");
return permutations;
}
List<Character> chars = new ArrayList<Character>(string.length());
for (char character : string.toCharArray()) {
chars.add(character);
}
Character firstChar = string.charAt(0);
String remainder = string.substring(1);
List<String> permutationsOfRemainder = Permutations.of(remainder);
for (String permutation : permutationsOfRemainder) {
for (int i = 0; i <= permutation.length(); i++) {
permutations.add(insertCharAt(permutation, firstChar, i));
}
}
return permutations;
}
private static String insertCharAt(String baseString,
Character charToInsert, int index) {
String start = baseString.substring(0, index);
String end = baseString.substring(index);
return start + charToInsert + end;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment