Print all permutations of a string in Java



Following is the Java program to print all permutations of a string −

Example

 Live Demo

public class Demo{
   static void print_permutations(String my_str,String my_ans){
      if (my_str.length() == 0){
         System.out.print(my_ans + " ");
         return;
      }
      boolean my_arr[] = new boolean[26];
      for (int i = 0; i < my_str.length(); i++){
         char ch = my_str.charAt(i);
         String remaining_str = my_str.substring(0, i) + my_str.substring(i + 1);
         if (my_arr[ch - 'a'] == false)
         print_permutations(remaining_str, my_ans + ch);
         my_arr[ch - 'a'] = true;
      }
   }
   public static void main(String[] args){
      String my_str = "hey";
      System.out.println("The permutation of the string are :");
      print_permutations(my_str, "");
   }
}

Output

The permutation of the string are :
hey hye ehy eyh yhe yeh

A class named Demo contains a static function ‘print_permutations’, which checks if a string is empty, and if it is, then the output is printed. Now, a Boolean array named ‘my_arr’ is assigned with a size of 36, wherein 'false' values are stored by default. Whenever an alphabet is used, its index in the array is changed to 'true'.

A 'for' loop is used to iterate over the length of the string and the ith character of the string is checked. The remaining part of the string without the ith character is assigned to a string named 'remaining_str'. If the character is not used, a recursive call to the function occurs. Otherwise, no function call occurs. In the main function, a string is defined and the function is called on this string.


Advertisements