java实现返回一个字符串所有排列

今天偶然看到了一个笔试题,觉得挺有意思,分享一下解题思路



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

第一个方法是驱动程序,它调用第二个方法并打印给定字符串的所有序列

如果给定字符换"abc" 则相继打印出,

abc
acb
bca
bac
cba
cab

并且要用递归的方式去实现

解题思路

定义方法二为 :将给定low放到给定数组的头部,对其后续部分进行无序冒泡

扫描二维码关注公众号,回复: 5279631 查看本文章
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); //递归调用
    }

}

猜你喜欢

转载自www.cnblogs.com/monkSand/p/10421158.html
今日推荐