Generating all permutations of a given string

前端 未结 30 1661
我寻月下人不归
我寻月下人不归 2020-11-21 06:35

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer st

相关标签:
30条回答
  • 2020-11-21 06:46

    This is what I did through basic understanding of Permutations and Recursive function calling. Takes a bit of time but it's done independently.

    public class LexicographicPermutations {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s="abc";
        List<String>combinations=new ArrayList<String>();
        combinations=permutations(s);
        Collections.sort(combinations);
        System.out.println(combinations);
    }
    
    private static List<String> permutations(String s) {
        // TODO Auto-generated method stub
        List<String>combinations=new ArrayList<String>();
        if(s.length()==1){
            combinations.add(s);
        }
        else{
            for(int i=0;i<s.length();i++){
                List<String>temp=permutations(s.substring(0, i)+s.substring(i+1));
                for (String string : temp) {
                    combinations.add(s.charAt(i)+string);
                }
            }
        }
        return combinations;
    }}
    

    which generates Output as [abc, acb, bac, bca, cab, cba].

    Basic logic behind it is

    For each character, consider it as 1st character & find the combinations of remaining characters. e.g. [abc](Combination of abc)->.

    1. a->[bc](a x Combination of (bc))->{abc,acb}
    2. b->[ac](b x Combination of (ac))->{bac,bca}
    3. c->[ab](c x Combination of (ab))->{cab,cba}

    And then recursively calling each [bc],[ac] & [ab] independently.

    0 讨论(0)
  • 2020-11-21 06:46
    /** Returns an array list containing all
     * permutations of the characters in s. */
    public static ArrayList<String> permute(String s) {
        ArrayList<String> perms = new ArrayList<>();
        int slen = s.length();
        if (slen > 0) {
            // Add the first character from s to the perms array list.
            perms.add(Character.toString(s.charAt(0)));
    
            // Repeat for all additional characters in s.
            for (int i = 1;  i < slen;  ++i) {
    
                // Get the next character from s.
                char c = s.charAt(i);
    
                // For each of the strings currently in perms do the following:
                int size = perms.size();
                for (int j = 0;  j < size;  ++j) {
    
                    // 1. remove the string
                    String p = perms.remove(0);
                    int plen = p.length();
    
                    // 2. Add plen + 1 new strings to perms.  Each new string
                    //    consists of the removed string with the character c
                    //    inserted into it at a unique location.
                    for (int k = 0;  k <= plen;  ++k) {
                        perms.add(p.substring(0, k) + c + p.substring(k));
                    }
                }
            }
        }
        return perms;
    }
    
    0 讨论(0)
  • 2020-11-21 06:48

    A very basic solution in Java is to use recursion + Set ( to avoid repetitions ) if you want to store and return the solution strings :

    public static Set<String> generatePerm(String input)
    {
        Set<String> set = new HashSet<String>();
        if (input == "")
            return set;
    
        Character a = input.charAt(0);
    
        if (input.length() > 1)
        {
            input = input.substring(1);
    
            Set<String> permSet = generatePerm(input);
    
            for (String x : permSet)
            {
                for (int i = 0; i <= x.length(); i++)
                {
                    set.add(x.substring(0, i) + a + x.substring(i));
                }
            }
        }
        else
        {
            set.add(a + "");
        }
        return set;
    }
    
    0 讨论(0)
  • 2020-11-21 06:49

    Well here is an elegant, non-recursive, O(n!) solution:

    public static StringBuilder[] permutations(String s) {
            if (s.length() == 0)
                return null;
            int length = fact(s.length());
            StringBuilder[] sb = new StringBuilder[length];
            for (int i = 0; i < length; i++) {
                sb[i] = new StringBuilder();
            }
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                int times = length / (i + 1);
                for (int j = 0; j < times; j++) {
                    for (int k = 0; k < length / times; k++) {
                        sb[j * length / times + k].insert(k, ch);
                    }
                }
            }
            return sb;
        }
    
    0 讨论(0)
  • 2020-11-21 06:50

    Use recursion.

    when the input is an empty string the only permutation is an empty string.Try for each of the letters in the string by making it as the first letter and then find all the permutations of the remaining letters using a recursive call.

    import java.util.ArrayList;
    import java.util.List;
    
    class Permutation {
        private static List<String> permutation(String prefix, String str) {
            List<String> permutations = new ArrayList<>();
            int n = str.length();
            if (n == 0) {
                permutations.add(prefix);
            } else {
                for (int i = 0; i < n; i++) {
                    permutations.addAll(permutation(prefix + str.charAt(i), str.substring(i + 1, n) + str.substring(0, i)));
                }
            }
            return permutations;
        }
    
        public static void main(String[] args) {
            List<String> perms = permutation("", "abcd");
    
            String[] array = new String[perms.size()];
            for (int i = 0; i < perms.size(); i++) {
                array[i] = perms.get(i);
            }
    
            int x = array.length;
    
            for (final String anArray : array) {
                System.out.println(anArray);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:50

    Here is a straightforward minimalist recursive solution in Java:

    public static ArrayList<String> permutations(String s) {
        ArrayList<String> out = new ArrayList<String>();
        if (s.length() == 1) {
            out.add(s);
            return out;
        }
        char first = s.charAt(0);
        String rest = s.substring(1);
        for (String permutation : permutations(rest)) {
            out.addAll(insertAtAllPositions(first, permutation));
        }
        return out;
    }
    public static ArrayList<String> insertAtAllPositions(char ch, String s) {
        ArrayList<String> out = new ArrayList<String>();
        for (int i = 0; i <= s.length(); ++i) {
            String inserted = s.substring(0, i) + ch + s.substring(i);
            out.add(inserted);
        }
        return out;
    }
    
    0 讨论(0)
提交回复
热议问题