Generating all permutations of a given string

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

    A java implementation to print all the permutations of a given string considering duplicate characters and prints only unique characters is as follow:

    import java.util.Set;
    import java.util.HashSet;
    
    public class PrintAllPermutations2
    {
        public static void main(String[] args)
        {
            String str = "AAC";
    
        PrintAllPermutations2 permutation = new PrintAllPermutations2();
    
        Set uniqueStrings = new HashSet<>();
    
        permutation.permute("", str, uniqueStrings);
    }
    
    void permute(String prefixString, String s, Set set)
    {
        int n = s.length();
    
        if(n == 0)
        {
            if(!set.contains(prefixString))
            {
                System.out.println(prefixString);
                set.add(prefixString);
            }
        }
        else
        {
            for(int i=0; i

提交回复
热议问题