Generating all permutations of a given string

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

    //insert each character into an arraylist

    static ArrayList al = new ArrayList();
    
    private static void findPermutation (String str){
        for (int k = 0; k < str.length(); k++) {
            addOneChar(str.charAt(k));
        }
    }
    
    //insert one char into ArrayList
    private static void addOneChar(char ch){
        String lastPerStr;
        String tempStr;
        ArrayList locAl = new ArrayList();
        for (int i = 0; i < al.size(); i ++ ){
            lastPerStr = al.get(i).toString();
            //System.out.println("lastPerStr: " + lastPerStr);
            for (int j = 0; j <= lastPerStr.length(); j++) {
                tempStr = lastPerStr.substring(0,j) + ch + 
                        lastPerStr.substring(j, lastPerStr.length());
                locAl.add(tempStr);
                //System.out.println("tempStr: " + tempStr);
            }
        }
        if(al.isEmpty()){
            al.add(ch);
        } else {
            al.clear();
            al = locAl;
        }
    }
    
    private static void printArrayList(ArrayList al){
        for (int i = 0; i < al.size(); i++) {
            System.out.print(al.get(i) + "  ");
        }
    }
    

提交回复
热议问题