java實現返回一個字符串所有排列


今天偶然看到了一個筆試題,覺得挺有意思,分享一下解題思路



public void permute(String string);
public void permute(char[] chars , int low , int high);

第一個方法是驅動程序,它調用第二個方法並打印給定字符串的所有序列

如果給定字符換"abc" 則相繼打印出,

abc
acb
bca
bac
cba
cab

並且要用遞歸的方式去實現

 

 

解題思路

 

定義方法二為 :將給定low放到給定數組的頭部,對其后續部分進行無序冒泡

 

public class Permute {
    public static void main(String[] args) {
        Permute aaa = new Permute();
        aaa.permute("abc");
    }

    public void permute(String string){
        char [] chars = string.toCharArray();
        permute(chars , 0 ,chars.length - 1);
    }

    public void permute(char[] chars , int low , int high){
        if (low > high) return ;

        char [] charsCopy = Arrays.copyOf(chars,chars.length);

        //把標記的元素放到串的頭部
        if(low != 0){
            char t = charsCopy[0];
            charsCopy[0] = charsCopy[low];
            charsCopy[low] = t;
        }

        //對后面的串進行冒泡
        String just = "" ;
        for (int i = 0 ; i < chars.length - 1 ; i++){
            for (int j = 1 ; j < chars.length - 1 ; j++){
                char t = charsCopy[j];
                charsCopy[j] = charsCopy[j + 1];
                charsCopy[j + 1] = t;

                just = new String(charsCopy);
                System.out.println(just);
                just = "";
            }
        }

        low++;
        permute(chars ,low , high); //遞歸調用
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM