Generating all permutations of a given string

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

    /*
         * eg: abc =>{a,bc},{b,ac},{c,ab}
         * =>{ca,b},{cb,a}
         * =>cba,cab
         * =>{ba,c},{bc,a}
         * =>bca,bac
         * =>{ab,c},{ac,b}
         * =>acb,abc
         */
        public void nonRecpermute(String prefix, String word)
        {
            String[] currentstr ={prefix,word};
            Stack stack = new Stack();
            stack.add(currentstr);
            while(!stack.isEmpty())
            {
                currentstr = stack.pop();
                String currentPrefix = currentstr[0];
                String currentWord = currentstr[1];
                if(currentWord.equals(""))
                {
                    System.out.println("Word ="+currentPrefix);
                }
                for(int i=0;i

提交回复
热议问题