Find all the permutations of a string - similar to permute arrays
Recursive Solution
Using Array Permutations
Here though we swap first and last characters recursively decrementing the last pointer, until first is equal to last character. The result for "abc" string is as below:
Example String: abcdefgh
When i = 0, we have, First wave of recursion till the String is empty
Input String: abcdefgh - "" + "bcdefgh" = "bcdefgh"
Input String: bcdefgh - "" + "cdefgh" = "cdefgh"
Input String: cdefgh - "" + "defgh" = "defgh"
Input String: defgh - "" + "efgh" = "efgh"
Input String: efgh - "" + "fgh" = "fgh"
Input String: fgh - "" + "gh" = "gh"
Input String: gh - "" + "h" = "h"
Input String: h - "" + "" = ""
Then coming out of recursion
Input String: gh - "g" + "" = "g"
Input String: g - "" + "" = ""
Input String: fgh - "f" + "h" = "fh"
Input String: fh - "" + "h" = "h"
Input String: h - "" + "" = ""
Input String: fh - "f" + "" = "f"
Input String: f - "" + "" = ""
Second round of for loop with i = 2
Input String: abcdefgh - "a" + "cdefgh" = "acdefgh"
Input String: acdefgh - "" + "cdefgh" = "cdefgh"
Input String: cdefgh - "" + "defgh" = "defgh"
Input String: defgh - "" + "efgh" = "efgh"
Input String: efgh - "" + "fgh" = "fgh"
Input String: fgh - "" + "gh" = "gh"
Input String: gh - "" + "h" = "h"
Input String: h - "" + "" = ""
And this continues. Here Permutations are printed in order of the string characters and duplicates would be present.
private static void perm1(String prefix, String s) { int n = s.length(); if (n == 0) System.out.println(prefix); else { for (int i = 0; i < n; i++) { perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, n)); } } }
We can also convert string to arrays and use permutations on them.
Here though we swap first and last characters recursively decrementing the last pointer, until first is equal to last character. The result for "abc" string is as below:
ABC
/ | \
ABC BAC CBA
/ \ / \ / \
ABC ACB BAC BCA CBA CAB
public static void main(String[] args) { String string = "abcdefgh"; perm2(string.toCharArray(), 0, string.length()-1); } private static void perm2(char[] a, int start, int end) { if (start == end) { System.out.println(new String(a)); } else { for (int i = start; i <= end; i++) { swap(a, start,i); permute(a, start+1, end); swap(a, start,i); } } } // swap the characters at indices i and j private static void swap(char[] a, int i, int j) { char c = a[i]; a[i] = a[j]; a[j] = c; }
Comments
Post a Comment