美文网首页
字符串的排列

字符串的排列

作者: 稀饭粥95 | 来源:发表于2018-08-29 15:54 被阅读2次

    输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

    public class Main3 {
        public char s[];
        public int length;
        public int use[];
        public Stack<Character> stack = new Stack<Character>();
        public ArrayList<String> list = new ArrayList<String>();
        public HashSet<String> dupCheck = new HashSet<String>();
         
        public void doPermutation(int size){
            if(size==length){
                Iterator<Character> iter = stack.iterator();
                StringBuilder strB = new StringBuilder();
                while(iter.hasNext()){
                    strB.append(iter.next());
                }
                String out = strB.toString();
                if(!dupCheck.contains(out)){
                    list.add(out);
                    dupCheck.add(out);
                }
                 
            }
            for(int i=0;i<length;i++){
                if(use[i]!=1){
                    stack.push(s[i]);
                    use[i]=1;
                    doPermutation(size+1);
                    use[i]=0;
                    stack.pop();
                }
            }
        }
         
         
        public ArrayList<String> Permutation(String str) {
            if(str.length()==0){
                return list;
            }
            length = str.length();
            s = new char[length];
            use = new int[length];
            for(int i=0;i<length;i++){
                s[i] = str.charAt(i);
            }
            doPermutation(0);
            return list;
        }
        
    
        public static void main(String[] args) {
            Main3 m= new Main3();
        }
    }
    

    相关文章

      网友评论

          本文标题:字符串的排列

          本文链接:https://www.haomeiwen.com/subject/mqkkwftx.html