Generate all permutations of a String in Java



 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 

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments