Finding all the unique permutations of a string without generating duplicates

前端 未结 5 1623
轻奢々
轻奢々 2020-11-28 10:03

Finding all the permutations of a string is by a well known Steinhaus–Johnson–Trotter algorithm. But if the string contains the repeated characters such as
AABB,
the

5条回答
  •  误落风尘
    2020-11-28 10:40

    This is a tricky question and we need to use recursion to find all the permutations of a String, for example "AAB" permutations will be "AAB", "ABA" and "BAA". We also need to use Set to make sure there are no duplicate values.

    import java.io.*;
    import java.util.HashSet;
    import java.util.*;
    class Permutation {
    
        static HashSet set = new HashSet();
        public static void main (String[] args) {
        Scanner in = new Scanner(System.in);
            System.out.println("Enter :");
            StringBuilder  str = new StringBuilder(in.nextLine());
            NONDuplicatePermutation("",str.toString());  //WITHOUT DUPLICATE PERMUTATION OF STRING
            System.out.println(set);
        }
    
    
        public static void NONDuplicatePermutation(String prefix,String str){
            //It is nlogn
            if(str.length()==0){
                set.add(prefix);
            }else{
                for(int i=0;i

提交回复
热议问题