Java Program to print distinct permutations of a string


To print distinct permutations of a string, the Java program is as follows −

Example

 Live Demo

import java.util.ArrayList;
public class Demo{
   static boolean is_present(String my_str, ArrayList<String> rem){
      for (String str : rem){
         if (str.equals(my_str))
         return true;
      }
      return false;
   }
   static ArrayList<String> distinct_pattern(String str){
      if (str.length() == 0){
         ArrayList<String> base_Val = new ArrayList<>();
         base_Val.add("");
         return base_Val;
      }
      char ch = str.charAt(0);
      String rem_str = str.substring(1);
      ArrayList<String> prev_str = distinct_pattern(rem_str);
      ArrayList<String> rem = new ArrayList<>();
      for (String my_str : prev_str){
         for (int i = 0; i <= my_str.length(); i++){
            String f = my_str.substring(0, i) + ch + my_str.substring(i);
            if (!is_present(f, rem))
            rem.add(f);
         }
      }
      return rem;
   }
   public static void main(String[] args){
      String my_str = "mnqm";
      System.out.println("The distinct permutations of the string are ");
      System.out.println(distinct_pattern(my_str));
   }
}

Output

The distinct permutations of the string are
[mnqm, nmqm, nqmm, mqnm, qmnm, qnmm, mqmn, qmmn, mnmq, nmmq, mmnq, mmqn]

A class named Demo contains a Boolean function named ‘is_present’ that checks to see if the string is actually present. It returns true or false depending on whether the string has some characters or not. Another function named ‘distinct_pattern’ creates an arraylist.

Another string is defined, named ‘rem_str’, that stores the substring of the string. This ‘distinct_function’ is called by passing the ‘rem_str’. In this way, the string is iterated over, and every character’s position is checked, before generating another distinct permutation. This way, all duplicates are avoided. In the end, all the unique permutations are displayed on the console. The main function defines the string, and the function ‘distinct_pattern’ is called on this string. The relevant output is displayed on the console.

Updated on: 14-Jul-2020

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements