Write a Java program that generates all permutations of a given string.
Java program to Generate all permutations
public final class JavaProgram{
public static void permuteAndPrint(String str) {
if (str == null || str.isBlank()) {
// or throw IllegalArgumentException
return;
}
permuteAndPrint("", str);
}
private static void permuteAndPrint(String prefix, String str) {
int n = str.length();
if (n == 0) {
System.out.print(prefix + " ");
} else {
for (int i = 0; i < n; i++) {
permuteAndPrint(prefix + str.charAt(i),
str.substring(i + 1, n) + str.substring(0, i));
}
}
}
}
Test
public class Main {
private static final String TEXT = "ABC";
public static void main(String[] args) {
System.out.println("Input text: \n" + TEXT + "\n");
System.out.println("Permute and print - recursive solution:");
JavaProgram.permuteAndPrint(TEXT);
System.out.println();
}
}
Output:
Input text:
ABC
Permute and print - recursive solution:
ABC ACB BCA BAC CAB CBA
Comments
Post a Comment