算法

获取字符串的全排列(去除字符串中2个字符相同时造成的重复)

2024-04-14  本文已影响0人  程序员小迷

一、概念

现有一个字符串,要打印出该字符串中字符的全排列。

以字符串abc为例,输出的结果为:abc、acb、bac、bca、cab、cba。

以字符串aab为例,输出的结果为:aab、aba、baa。

二、代码

public class Permutation {

    public static void main(String[] args) {

        List<String> list = getPermutation("abca");

//        输出结果

        dump(list);

    }

//    输出结果

    public static void dump(List<String> list) {

        if (null != list) {

            for (String str : list) {

                System.out.println(str);

            }

        }

    }

//    从字符串str获取全排列结果

    public static List<String> getPermutation(String str) {

        if (null == str) {

            return null;

        }

        char[] array = str.toCharArray();

        Arrays.sort(array);

        List<String> list = new ArrayList<>();

//        进行全排列操作

        permutationIteration(array, 0, list);

        Collections.sort(list);

        return list;

    }

//    全排列操作

    public static List<String> permutationIteration(char[] array, int index, List<String> list) {

        //到达子递归操作的最后,将结果加入列表

        if (index == array.length - 1) {

            list.add(String.valueOf(array));

            return list;

        }

        for (int i = index; i < array.length; i++) {

            //当要交换的字符值相同时,则交换是使结果重复的操作,故不予交换

            if (i != index && array[i] == array[index]) {

                continue;

            }

            //交换2个位置的字符

            swap(index, i, array);

//            递归调用获取结果

            permutationIteration(array, index + 1, list);

//          将交换操作还原回去

            swap(index, i, array);

        }

        return list;

    }

    /**

    * array:  字符数组

    * 交换字符数组中2个位置的字符

    */

    public static void swap(int index1, int index2, char[] array) {

        if (index1 != index2) {

            char tmp = array[index1];

            array[index1] = array[index2];

            array[index2] = tmp;

        }

    }

}


致力于C、C++、Java、Kotlin、Android、Shell、JavaScript、TypeScript、Python等编程技术的技巧经验分享。

若作品对您有帮助,请关注、分享、点赞、收藏、在看、喜欢。您的支持是我们为您提供帮助的最大动力。

上一篇 下一篇

猜你喜欢

热点阅读