Generating all permutations of a given string

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

    One of the simple solution could be just keep swapping the characters recursively using two pointers.

    public static void main(String[] args)
    {
        String str="abcdefgh";
        perm(str);
    }
    public static void perm(String str)
    {  char[] char_arr=str.toCharArray();
        helper(char_arr,0);
    }
    public static void helper(char[] char_arr, int i)
    {
        if(i==char_arr.length-1)
        {
            // print the shuffled string 
                String str="";
                for(int j=0; j

提交回复
热议问题