arrangement of strings

topic

Enter a string and print out all permutations of the characters in the string lexicographically. For example, if the string abc is input, all strings abc, acb, bac, bca, cab and cba that can be arranged by the characters a, b, and c are printed out. (Enter a string with a length of no more than 9 (there may be repeated characters), and the characters only include upper and lower case letters.)

For the full arrangement of all characters in the string, just pay attention to the repeated arrangement.


import java.util.ArrayList;

public class Solution {
    private int length = 0;

    public ArrayList<String> Permutation(String str) {
        length = str.length();

        return per(str);
    }

    private ArrayList<String> per(String str) {
        ArrayList<String> list = new ArrayList<>();
        if (str.length() == 1) {
            list.add(str);
        }
        else {
            for (int i=0; i<str.length(); i++) {
                String subStr = str.substring(0, i) + str.substring(i+1, str.length());
                ArrayList<String> subList = per(subStr);
                for (String s : subList) {
                    String newStr = str.substring(i,i+1) + s;
                    if (newStr.length() == length && list.contains(newStr))
                        continue;
                    list.add(newStr);
                }
            }
        }
        return list;
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325332171&siteId=291194637