字符串的排列

2018-08-29  本文已影响2人  稀饭粥95

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串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();
    }
}
上一篇下一篇

猜你喜欢

热点阅读