Skip to content

Instantly share code, notes, and snippets.

@nickrobson
Last active November 1, 2016 00:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nickrobson/89bd549162c1856d6761011cf3f4ccaf to your computer and use it in GitHub Desktop.
Gets all permutations of a string.
public class Permute {
public static void main(String[] args) {
for (String res : permute(args.length > 0 ? args[0] : "AABC")) {
System.out.println(res);
}
}
public String[] permute(String str) {
if (str.length() <= 1)
return new String[]{ str };
String[] endPermute = permute(str.substring(1));
Set<String> output = new LinkedHashSet<>();
for (int i = 0, j = endPermute.length; i < j; i++) {
String ep = endPermute[i];
for (int k = 0, l = ep.length(); k <= l; k++) {
output.add(ep.substring(0, k) + str.charAt(0) + ep.substring(k));
}
}
String[] out = output.toArray(new String[0]);
Arrays.sort(out);
return out;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment