Generating all permutations of a given string

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

    A very basic solution in Java is to use recursion + Set ( to avoid repetitions ) if you want to store and return the solution strings :

    public static Set generatePerm(String input)
    {
        Set set = new HashSet();
        if (input == "")
            return set;
    
        Character a = input.charAt(0);
    
        if (input.length() > 1)
        {
            input = input.substring(1);
    
            Set permSet = generatePerm(input);
    
            for (String x : permSet)
            {
                for (int i = 0; i <= x.length(); i++)
                {
                    set.add(x.substring(0, i) + a + x.substring(i));
                }
            }
        }
        else
        {
            set.add(a + "");
        }
        return set;
    }
    

提交回复
热议问题