剑指offer面试题38:字符串的排列(Java 实现)

题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。

思路:

第一步求所有可能出现在第一个位置的字符,固定第一个字符,然后遍历后面的所有字符和它交换;第二步求所有可能出现在第二个位置的字符,固定第二个字符,然后遍历后面所有字符与它交换;第三步。。。同样,很明显这个一个递归的过程,构造一个递归函数进行实现。需要注意的是每一个交换字符后都要交换回来,以便当下字符与其它字符的交换。

测试用例:

  1. 功能测试:输入的字符串有一个或者多个字符。
  2. 特殊测试:输入的字符串的内容为空。
public class test_thirty_eight {
    public ArrayList<String> Permutation(String str){
        ArrayList<String> list = new ArrayList<String>();

        if (str == null || str.length() == 0)return list;

        //把字符串转化为字符数组
        char[] chars = str.toCharArray();

        //用来存放每一个递归交换后的字符串
        TreeSet<String> temp = new TreeSet<>();
        Permutation(chars, 0 , temp);
        list.addAll(temp);
        return list;
    }

    public void Permutation(char[] chars, int index, TreeSet<String> list) {
        if (chars == null || chars.length == 0)return;

        if (index < 0 ||index > chars.length-1)return;   //字符数组的下标

        //遍历到字符串数组的最后一个元素,直接把整个字符数组转化为字符串形式
        if (index == chars.length-1){
            list.add(String.valueOf(chars));
        } else{
            for (int i = index; i<chars.length-1; i++){  //遍历数组中的每一个字符
                swap(chars, index, i);  //把第一个字符和它后面所有的字符进行交换
                Permutation(chars, index+1, list);   //递归对后面所有的字符进行全排列
                swap(chars, index, i);  //把之前交换的字符交换回来,以便第一个字符与其它字符交换
            }
        }
    }

    public void swap(char[] chars, int index, int i) {
        char temp = chars[index];
        chars[index] = chars[i];
        chars[i] = temp;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41163113/article/details/86593152