Generating all permutations of a given string

前端 未结 30 2132
我寻月下人不归
我寻月下人不归 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

    /** Returns an array list containing all
     * permutations of the characters in s. */
    public static ArrayList permute(String s) {
        ArrayList 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;
    }
    

提交回复
热议问题