fork(7) download
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class Main
  5. {
  6. public static void main(String[] args)
  7. {
  8. Scanner sc = new Scanner(System.in);
  9. System.out.println("Enter the string:");
  10. String s = sc.nextLine();
  11. char[] c = s.toCharArray();
  12. Arrays.sort(c);
  13.  
  14. System.out.println("Here are all the permutations:");
  15. Main.c = c;
  16. count = 0;
  17. permutation(0);
  18. System.out.println("Number of permutations = " + count);
  19. }
  20.  
  21. static char[] c;
  22. static int count;
  23.  
  24. static void swap(int pos1, int pos2)
  25. {
  26. char temp = c[pos1];
  27. c[pos1] = c[pos2];
  28. c[pos2] = temp;
  29. }
  30.  
  31. public static void permutation(int start)
  32. {
  33. if (start == c.length)
  34. {
  35. System.out.println(c);
  36. count++;
  37. }
  38.  
  39. for (int i = start; i < c.length; i++)
  40. {
  41. if (i == start || (c[i] != c[i-1] && c[i] != c[start]))
  42. {
  43. swap(start, i);
  44. permutation(start + 1);
  45. swap(start, i);
  46. }
  47. }
  48. }
  49. }
Success #stdin #stdout 0.09s 380608KB
stdin
bell
stdout
Enter the string:
Here are all the permutations:
bell
blel
blle
ebll
elbl
ellb
lebl
lelb
lbel
lble
llbe
lleb
Number of permutations = 12