Write a Java Program to Compute all the permutations of the string

Write a Java Program to Compute all the permutations of the string

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

class Main {
  public static Set<String> getPermutation(String str) {

    // create a set to avoid duplicate permutation
    Set<String> permutations = new HashSet<String>();

    // check if string is null
    if (str == null) {
      return null;
    } else if (str.length() == 0) {
      // terminating condition for recursion
      permutations.add("");
      return permutations;
    }

    // get the first character
    char first = str.charAt(0);

    // get the remaining substring
    String sub = str.substring(1);

    // make recursive call to getPermutation()
    Set<String> words = getPermutation(sub);

    // access each element from words
    for (String strNew : words) {
      for (int i = 0;i<=strNew.length();i++){

        // insert the permutation to the set
        permutations.add(strNew.substring(0, i) + first + strNew.substring(i));
      }
    }
    return permutations;
  }

  public static void main(String[] args) {

    // create an object of scanner class
    Scanner input = new Scanner(System.in);

    // take input from users
    System.out.print("Enter the string: ");
    String data = input.nextLine();
    System.out.println("Permutations of " + data + ": \n" + getPermutation(data));
    }
}

Final output

Leave a Comment