Smart way to generate permutation and combination of String

前端 未结 7 446
耶瑟儿~
耶瑟儿~ 2021-02-01 22:37
String database[] = {\'a\', \'b\', \'c\'};

I would like to generate the following strings sequence, based on given database.



        
7条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 23:21

    // IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!
    
    import java.util.*;
    public class Permutation {
    
        public static void main(String[] args) {
            Scanner in=new Scanner(System.in);
            System.out.println("ENTER A STRING");
            Set se=find(in.nextLine());
            System.out.println((se));
        }
        public static Set find(String s)
        {
            Set ss=new HashSet();
            if(s==null)
            {
                return null;
            }
            if(s.length()==0)
            {
                ss.add("");
            }
            else
            {
                char c=s.charAt(0);
                String st=s.substring(1);
                Set qq=find(st);
                for(String str:qq)
                {
                    for(int i=0;i<=str.length();i++)
                    {
                        ss.add(comb(str,c,i));
                    }
                }
            }
            return ss;
    
        }
        public static String comb(String s,char c,int i)
        {
            String start=s.substring(0,i);
            String end=s.substring(i);
            return start+c+end;
        }
    
    }
    
    
    // IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!
    

提交回复
热议问题