This is a tricky question and we need to use recursion to find all the permutations of a String, for example “AAB” permutations will be “AAB”, “ABA” and “BAA”.
We also need to use Set to make sure there are no duplicate values.
Check this post for complete program to find all permutations of String.
import java.util.HashSet;
import java.util.Set;
public class StringExample
{
public static void main(String[] args)
{
System.out.println(getPermutations("ABC"));
}
public static Set<String> getPermutations(String string)
{
Set<String> permutationsSet = new HashSet<String>();
if (string == null || string.length() == 0)
{
permutationsSet.add("");
}
else
{
char initial = string.charAt(0);
String rem = string.substring(1);
Set<String> wordSet = getPermutations(rem);
for (String word : wordSet) {
for (int i = 0; i <= word.length(); i++) {
permutationsSet.add(charInsertAt(word, initial, i));
}
}
}
return permutationsSet;
}
public static String charInsertAt(String str, char c, int position)
{
String begin = str.substring(0, position);
String end = str.substring(position);
return begin + c + end;
}
}