Program to Print Permutations of a String

      Comments Off on Program to Print Permutations of a String




Permutations of a String refer to all possible Strings formed by rearrangement of characters a String.

The below program prints all possible words formed by rearrangement of characters of a String. It prints all words of a String containing distinct characters.

If one or more characters of a String are same , then words formed by permutations which are same can be filtered from the list and only distinct words can be printed.

package com.masterjavatutorial;
import java.util.ArrayList;
import java.util.List;

public class Example {
	

	public static void main(String[] args) {
    	  String str=  "ABC";
	      List permutate = permutate(str);
	      System.out.println(permutate);  
	      System.out.println(permutate.size());   
	}

	private static List permutate(String str) {

		if(str == null) {
		    return null;
		}
		List ltr = new ArrayList();
		if(str.length() == 1) {
		    ltr.add(str);
		    return ltr;
		}
		 
		char charAt = str.charAt(0); 
		List permutate = permutate(str.substring(1, str.length())); 
		for(String st : permutate){
		    for(int i=0;i<(st.length()+1);i++) {
			if( i ==0) {
			    ltr.add(charAt +""+st);
			}else if(i == st.length()) {
			    ltr.add(st+""+charAt);
			}else {
			    ltr.add(st.substring(0, i)+""+charAt+""+st.substring(i)); 
			}
		    }
		}
		return ltr;
	}

}

Output of the above Program is as below:

[ABC, BAC, BCA, ACB, CAB, CBA]
No of permutations = 6