Find All Permutation of a given String in Easy Way
1 min readDec 24, 2021
See possible permutations of string “ABC” in the picture
Now what can we see from the picture that for first step, We have to rotate character at first position to every next position in given String ABC.
in 2nd step , we have to rotate 2nd character position with every next position in the List of Strings which we get from step 1 and so on.
So this is only the solution and can be implemented below like:
We can take a map/set to store the result to avoid duplicate items.That’s it.
import java.util.HashSet;
public class StringPermutation {
public static void main(String[] args){
HashSet<String> output = new HashSet<>();
String input = "ABC";
doPermutation(input, output);
System.out.println(output);
}
private static void doPermutation(String input, HashSet<String> set) {
HashSet<String> inputList = new HashSet<>();
inputList.add(input);
for(int i=0; i<input.length()-1; i++){
int finalI = i;
inputList.forEach((k) -> {
for (int j = finalI; j < input.length(); j++) {
set.add(swap(k, finalI, j));
}
});
inputList = (HashSet<String>) set.clone();
}
}
private static String swap(String str, int firstIndex, int secondIndex) {
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(firstIndex, str.charAt(secondIndex));
sb.setCharAt(secondIndex, str.charAt(firstIndex));
return sb.toString();
}
}