Skip to content

Instantly share code, notes, and snippets.

@sonyakc
Created December 30, 2018 16:25
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 sonyakc/e6c0c93c0e9dae977141105726535e79 to your computer and use it in GitHub Desktop.
Save sonyakc/e6c0c93c0e9dae977141105726535e79 to your computer and use it in GitHub Desktop.
Output all permutations of a given string
import java.util.LinkedHashSet;
import java.util.Set;
public class Permutation {
public static void main(String[] args) {
String str = "sonya"; // 5 * 4 * 3 * 2 = 20 * 6 = 120
Permutation permutation = new Permutation();
StringBuilder builder = new StringBuilder();
Set<String> permSet = new LinkedHashSet<>();
permutation.permute(str, builder, permSet);
for (String s : permSet) {
System.out.println(s);
}
System.out.println(permSet.size());
}
public static void indent(int amount) {
for (int i = 0; i < amount; i++) {
System.out.print(' ');
}
}
private void permute(final String str, final StringBuilder builder, final Set<String> permSet) {
// indent(builder.length());
// System.out.println("permute(" + str + "," + builder.toString() + ")");
if (str == null || str.isEmpty()) {
permSet.add(builder.toString());
} else {
int n = str.length();
for (int i = 0; i < n; i++) {
// choose 1 letter
char c = str.charAt(i);
String substring = str.replaceFirst(Character.toString(c), "").trim();
builder.append(c);
// explore
permute(substring, builder, permSet);
// un-choose
builder.deleteCharAt(builder.length() - 1);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment