求一个字符串的全排列

求输出一个字符串的全排列的程序?

例如输入“ab”,输出:“ab”“ba”
输入“abc”输出:“abc”“acb”“bac”“bca”“cab”“cba”,

设输入的字符串是“hello_world”
public class Main{
    
    public static void main(String[] args) {
        System.out.println(permutation("ab").length);
        System.out.println(Arrays.toString(permutation("ab")));
    }
    
    private static String[] permutation(String orginal){
        ArrayList list = new ArrayList();
        if(orginal.length() == 1){
            return new String[]{orginal};
        } else{
            for (int i = 0; i < orginal.length(); i++) {
                String s = orginal.charAt(i) + "";
                String result = "";
                String resultA = result + s;
                String leftS = orginal.substring(0, i) + orginal.substring(i + 1, orginal.length());
                for (String element : permutation(leftS)) {
                    result = resultA + element;
                    list.add(result);
                }
            }
            return (String[]) list.toArray(new String[list.size()]);
        }
    }    
}

你可能感兴趣的:(字符串)