Last active
November 1, 2016 00:06
Star
You must be signed in to star a gist
Gets all permutations of a string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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