Skip to content

Instantly share code, notes, and snippets.

@unnisworld
Last active December 21, 2015 02:59
Show Gist options
  • Save unnisworld/6239262 to your computer and use it in GitHub Desktop.
Save unnisworld/6239262 to your computer and use it in GitHub Desktop.
Java code to print permutation of a String. Impl is based on logic described here - http://www.ardendertat.com/2011/10/28/programming-interview-questions-11-all-permutations-of-string/
import java.util.List;
import java.util.ArrayList;
public class Test {
public static void main(String []args)
{
List<String> output = permut("ABC");
System.out.println("===== Output =====");
for (String str : output)
{
System.out.println(str);
}
}
// permutOf("ABC") = madInsert(A, permutOf("BC"))
private static List<String> permut(String str)
{
System.out.println("Finding permutation of "+str);
List<String> perms = new ArrayList<String>();
// Permutation of "A" is "A" itself.
if (str.length() == 1)
{
perms.add(str);
return perms;
}
// Keep the Nth char aside. Keep aside "A" from "ABC"
String firstChar = str.substring(0,1);
// Find permutation of N-1 chars. To find permute of "ABC", find permute of "BC".
List<String> nMinusOnePermsOutput = permut(str.substring(1));
// Insert Nth Char into all positions of N-1 Permutation O/P. Insert "A" into permuteOf("BC")
perms = madInsert(firstChar, nMinusOnePermsOutput);
return perms;
}
// This method iterates over each item in the N-1 o/p and inserts Nth char into it.
private static List<String> madInsert(String firstChar, List<String> nMinusOnePermsOutput)
{
List<String> outputList = new ArrayList<String>();
for (String str : nMinusOnePermsOutput) {
outputList.addAll(insertChar(str, firstChar));
}
return outputList;
}
// Insert Nth char into all possible locations of current string.
// For eg:- for inputs char 'A' and String "BC", o/p will be "ABC", "BAC" and "BCA".
private static List<String> insertChar(String str, String firstChar)
{
System.out.println("Inserting "+ firstChar + " into " + str);
List<String> outputList = new ArrayList<String>();
for (int i=0;i<=str.length();i++)
{
StringBuffer sb = new StringBuffer(str);
sb.insert(i, firstChar);
outputList.add(sb.toString());
}
return outputList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment