Print all permutations of String
Example:
Input: str="Java"
Output: All the permutations:
Java, Jaav, Jvaa, Jvaa, Java, Jaav, aJva, aJav, avJa, avaJ, aavJ, aaJv, vaJa, vaaJ, vJaa, vJaa, vaJa, vaaJ, aavJ, aaJv, avaJ, avJa, aJva, aJav,
Approach
Java
public class PermuteStringGen {public static void main(String[] args) {String str = "Java";int len = str.length();System.out.println("All the permutations: ");genPermutationS(str, 0, len);}// Method to generate all permutationspublic static void genPermutationS(String str, int start, int end) {// Prints the permutationsif (start == end - 1)System.out.print(str + ", ");else {for (int i = start; i < end; i++) {// Swapping the string by fixing a characterstr = strSwap(str, start, i);// Recursively callinggenPermutationS(str, start + 1, end);// Backtracking and swapping the characters again.str = strSwap(str, start, i);}}}// Swappublic static String strSwap(String a, int i, int j) {char[] b = a.toCharArray();char ch;ch = b[i];b[i] = b[j];b[j] = ch;return String.valueOf(b);}}
No comments:
Post a Comment