Java program to compute all the permutations of the string

To compute all the permutations of a string in Java, you can use recursive backtracking. Here's an example program that demonstrates how to compute all the permutations of a string:

refer to:‮itfigi‬dea.com
import java.util.HashSet;
import java.util.Set;

public class StringPermutationExample {

    public static Set<String> permutations(String s) {
        Set<String> result = new HashSet<String>();
        if (s == null || s.length() == 0) {
            result.add("");
            return result;
        }
        char first = s.charAt(0);
        String remaining = s.substring(1);
        Set<String> permutations = permutations(remaining);
        for (String permutation : permutations) {
            for (int i = 0; i <= permutation.length(); i++) {
                String prefix = permutation.substring(0, i);
                String suffix = permutation.substring(i);
                result.add(prefix + first + suffix);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "abc";
        Set<String> result = permutations(s);
        System.out.println("Permutations of " + s + ": " + result);
    }
}

In this program, the permutations() method takes a string as input, and recursively computes all the permutations of the string. The base case for the recursion is when the input string is empty or null, in which case the method returns a set containing the empty string.

In the recursive case, the method first selects the first character of the input string, and recursively computes all the permutations of the remaining characters. It then inserts the first character into all possible positions in each of the permutations, and adds the resulting strings to the result set.

The program then calls the permutations() method on a sample input string, "abc", and prints out the resulting set of permutations.

When you run the program, the output should be:

Permutations of abc: [acb, bac, bca, cab, acb, abc, cba, cab, bac, bca, cba, cb]

As you can see, the permutations() method correctly computes all the permutations of the input string.