Print all permutations of String in java - Java @ Desk

Thursday, September 26, 2013

Print all permutations of String in java















import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class StringPermutations {
    static Set permutationSet;

    static Set permutationResult = new HashSet();

    public static Set permutation(String string) {
        permutationSet = new HashSet();

        int length = string.length();
        for (int i = length - 1; i >= 0; i--) {
            shuffle(string.charAt(i));
        }
        return permutationSet;
    }

    private static void shuffle(char c) {
        if (permutationSet.size() == 0) {
            permutationSet.add(String.valueOf(c));
        } else {
            Iterator it = permutationSet.iterator();
            for (int i = 0; i < permutationSet.size(); i++) {

                String temp;
                for (; it.hasNext();) {
                    temp = it.next();
                    for (int k = 0; k < temp.length() + 1; k += 1) {
                        StringBuilder sb = new StringBuilder(temp);

                        sb.insert(k, c);

                        permutationResult.add(sb.toString());
                    }
                }
            }
            permutationSet = permutationResult;
            permutationResult = new HashSet();
        }
    }

    public static void main(String[] args) {
        Set result = permutation("abc");

        Iterator it = result.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}







No comments:

Post a Comment