Description
Write a java program to find all the permutations of any given string. Permutation is the each of several possible ways in which a set or number of things can be ordered or arranged. Order matters in case of Permutation. For example, the permutation of ab will be ab and ba. A string of length n can have a permutations of n!. Following is the java program to find permutation of a given string.
The approach would be to take out the first char and keep it constant and permute the rest of the characters and use recursion to permute the rest of the string except the first character. While making the recursive call, we accumulate each character being constant along with recursive call response.
StringPermutations.javapackage com.devglan; import java.util.ArrayList; import java.util.List; public class StringPermutations { public ListgetPermutations(String input) { List strList = new ArrayList<>(); permutations("", input, strList); return strList; } public void permutations(String consChars, String input, List list) { if(input.isEmpty()) { list.add(consChars + input); return; } for(int i = 0; i < input.length(); i++) { permutations(consChars + input.charAt(i), input.substring(0, i)+input.substring(i+1), list); } } public static void main(String a[]) { StringPermutations permutations = new StringPermutations(); List output = permutations.getPermutations("india"); System.out.println("Result size: "+output.size()); output.stream().forEach(System.out::println); } }