Tuesday, November 3, 2015

Find Permutations of a String Recursively in Java

In order to print all the permutations of a String a recursive method can be implemented.

In this recursive String permutation solution a StringBuilder instance is used as compared to other common String permutation implementations in Java.


package basics;

public class StringUtils {

 public static void permute( String str ) {
  print("", str);
 }

 private static void print(String leftPart, String str ) {

  int sLength = str.length();
  if ( sLength == 0) {
   return;
  } else if ( sLength == 1) {
   System.out.println(leftPart + str);
   return;
  }

  StringBuilder buffer = new StringBuilder(str);

  for (int i = 0; i < sLength; i++) {
   char temp = buffer.charAt(i);
   buffer.setCharAt(i, buffer.charAt(0));
   buffer.setCharAt( 0, temp );
   print( leftPart + temp, buffer.substring(1, sLength) );
  }
  
 }
 
 public static void main(String[] args) {
  
  String val = "abc"; 
  System.out.println("All Permutations of "+val);
  permute(val);  
  val = "abcd";
  System.out.println("All Permutations of "+val);
  permute(val);
  
 }

}



Create a StringUtils.java file in your workspace.

When the main method inside the StringUtils class executed it is going to print :

All Permutations of abc
abc
acb
bac
bca
cab
cba
All Permutations of abcd
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba

No comments:

Post a Comment