Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created August 16, 2014 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislukkk/9edbe69c5223c05f1235 to your computer and use it in GitHub Desktop.
Save chrislukkk/9edbe69c5223c05f1235 to your computer and use it in GitHub Desktop.
Career cup 9.5
package Chapter9;
import java.util.ArrayList;
public class StringPermutation {
public static ArrayList<String> getAllPermutations(String s) {
ArrayList<String> permutations = new ArrayList<>();
permutations.add("");
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
ArrayList<String> newPermutations = new ArrayList<String>();
for (String perm : permutations) {
for(int j = 0; j <= perm.length(); j++) {
newPermutations.add(perm.substring(0, j) + c + perm.substring(j));
}
}
permutations = newPermutations;
newPermutations = null;
}
return permutations;
}
public static void printPerms(ArrayList<String> perms) {
for (String perm : perms) {
System.out.println(perm);
}
System.out.println("total " + perms.size() +" permutations");
}
public static void main(String[] args) {
String testString = "HelloWorld";
printPerms(getAllPermutations(testString));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment