Google News
logo
Java Program to Compute all the Permutations of the String
In the following example of Java program that computes all permutations of a string :
Program :
public class StringPermutations {
    public static void main(String[] args) {
        String str = "ABC";
        System.out.println("Permutations of " + str + ":");
        permute(str, 0, str.length() - 1);
    }
    
    public static void permute(String str, int left, int right) {
        if (left == right) {
            System.out.println(str);
        } else {
            for (int i = left; i <= right; i++) {
                str = swap(str, left, i);
                permute(str, left + 1, right);
                str = swap(str, left, i);
            }
        }
    }
    
    public static String swap(String str, int i, int j) {
        char[] charArray = str.toCharArray();
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
        return String.valueOf(charArray);
    }
}
Output :
Permutations of ABC:ABC
ACB
BAC
BCA
CBA
CAB
In this program, we first define a string str. We then call the permute() method, which takes three arguments: the string str, the left index left, and the right index right. The permute() method computes all permutations of the substring of str that starts at index left and ends at index right.

The permute() method first checks whether left is equal to right. If they are equal, it prints the current permutation of str to the console. Otherwise, it loops through all possible positions of the character at index left, and recursively computes all permutations of the substring that starts at index left + 1 and ends at index right. It also swaps the characters at positions left and i in str before and after the recursive call to ensure that all possible permutations are computed.

The swap() method is a helper method that takes a string str and two indices i and j, and swaps the characters at positions i and j in str. It then returns the modified string.