Wednesday, 25 October 2017

Print All subsets of a strings in lexicographically(As occur in Dictionary) order

import java.io.IOException;
import java.util.*;
class Main
{
     public static void main(String[] args) {
     String input = "abc";
     Set<String> returnList = permutations(input);
     System.out.println(returnList);
    }

    private static Set<String> permutations(String input) {
      if (input.length() == 1) {
        Set<String> a = new TreeSet<>();
        a.add(input);
        return a;
      }
    Set<String> returnSet = new TreeSet<>();

    for (int i = 0; i < input.length(); i++) {
         String prefix = input.substring(i, i + 1);
         Set<String> permutations = permutations(input.substring(i + 1));
         returnSet.add(prefix);
         returnSet.addAll(permutations);
         Iterator<String> it = permutations.iterator();
         while (it.hasNext()) {
          returnSet.add(prefix + it.next());
         }
     }
    return returnSet;
  }
}

Output:
[a, ab, abc, ac, b, bc, c]