Advertisement
Guest User

PermutationsOfString

a guest
May 27th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1. import java.util.List;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4.  
  5. public class PermutationsNoDuplicates {
  6.  
  7.     public static void main(String[] args) {
  8.         printStrings(getAllPermutations("abdc"));
  9.  
  10.     }
  11.  
  12.     public static void printStrings(List<String> abc) {
  13.         System.out.println(abc.size());
  14.         for (String s : abc) {
  15.             System.out.println(s);
  16.         }
  17.     }
  18.  
  19.     public static List<String> getAllPermutations(String s) {
  20.         if (s.length() == 1) {
  21.             return Collections.singletonList(s);
  22.         } else {
  23.             char c = s.charAt(0);
  24.             List<String> permutationsInner = getAllPermutations(s.substring(1,
  25.                     s.length()));
  26.             return insertCharAtAllLocationsInStrings(c, permutationsInner);
  27.         }
  28.     }
  29.  
  30.     public static List<String> insertCharAtAllLocationsInStrings(char c,
  31.             List<String> strings) {
  32.         List<String> permutations = new ArrayList<>();
  33.         for (String s : strings) {
  34.             List<String> permutationsForS = insertCharAtAllLoc(c, s);
  35.             permutations.addAll(permutationsForS);
  36.         }
  37.         return permutations;
  38.     }
  39.  
  40.     public static List<String> insertCharAtAllLoc(char c, String s) {
  41.         List<String> strings = new ArrayList<>();
  42.         int locationToInsert = 0;
  43.  
  44.         // Now iterate through the string
  45.         for (locationToInsert = 0; locationToInsert < s.length() + 1; locationToInsert += 1) {
  46.             char[] array = new char[s.length() + 1];
  47.             for (int j = 0, i = 0; j < s.length() + 1; j++) {
  48.                 if (j == locationToInsert) {
  49.                     array[j] = c;
  50.                 } else {
  51.                     array[j] = s.charAt(i);
  52.                     i += 1;
  53.                 }
  54.  
  55.             }
  56.             strings.add(String.valueOf(array));
  57.         }
  58.         return strings;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement