Search code examples
javaperformancepermutation

Permutate every combination to the letter


public class StringPermutation {    
    public static List<String> getPermutation(String input) {
        List<String> collection = null;   
        if (input.length() == 1) {
            collection = new ArrayList<String>();
            collection.add(input);
            return collection;
        } else {
            collection = getPermutation(input.substring(1));
            Character first = input.charAt(0);
            List<String> result = new ArrayList<String>();
            for (String str : collection) {
                for (int i = 0; i < str.length(); i++) {
                    String item = str.substring(0, i) + first
                            + str.substring(i);
                    result.add(item);
                }
                String item = str.concat(first.toString());
                result.add(item);
            }
            return result;
        }
    }

    public static void main(String[] args) {
        List<String> test = StringPermutation.getPermutation ("CAT");
        System.out.println (test);
    }
}

The code above permutes a string it's given. For example, given cat, it returns [cat, act, atc, cta, tca, tac], which is excellent but is it possible for you guys to please edit my code so that it also shows the subsets of the letters too, i.e [cat, act, atc, cta, tca, tac] and [at, ta, tc, ca, ac, ct, c, a, t]?


Solution

  • I think you can first generate all subsets of letters and then generate all permutations for given subset:

    Set<String> subsets;
    
    public void generateSubsets(String current, String left) {
        if (left.length() == 0) {
            subsets.add(current);
        } else {
            generateSubsets(current, left.substring(1));
            generateSubsets(current + left.charAt(0), left.substring(1));
        }
    }
    
    List<String> allPermutations(String word) {
        subsets = new HashSet<String>();
        generateSubsets("", word);
        List<String> result = new ArrayList<String>();
        for (String subset : subsets) {
            result.addAll(StringPermutation.getPermutation(subset));
        }
        return result;
    }
    

    So if you have "cat" Subsets will be: "", "c", "a", "t", "ca", "ct", "tc", "cat" And then you get permutations for every subset.
    Regarding efficiency, it is not the best solution, but you can improve it.