java得到不重复的全排列字母题解

字符串的排列

http://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7

思想就是利用hashSet,对字符串中的字符两两转换,hashSet中保存转换的结果,然后对字符串数组进行转换,知道得到的hashSet中的字符串数量不再改变为止。

import java.util.*;
public class Solution {
    public ArrayList<String> Permutation(String str) {
        if(str==null || str.length()==0)
            return new ArrayList<String>();
        char[] chars = str.toCharArray();
        LinkedHashSet<String> results = new LinkedHashSet<>();
        ArrayList<String> strings = new ArrayList<>();
        results.add(new String(chars));
        strings.add(str);

        int len2 =results.size();
        int index = 0;
        while (index<len2) {
            chars = strings.get(index).toCharArray();
            index++;
            for (int i = chars.length - 1; i >= 0; i--) {
                for (int j = 0; j <= i; j++) {
                    results.addAll(getStr(chars, j, i));
                }
            }
            strings = new ArrayList<>();
            strings.addAll(results);
            Collections.sort(strings);
            len2=results.size();
        }
        Collections.sort(strings);
        return strings;
    }

    public ArrayList<String> getStr(char[] chars,int index,int right){
        ArrayList<String> strings = new ArrayList<>();
        if(index>right)
            return strings;
        char temp = chars[index];
        ArrayList<String> result = new ArrayList<>();
        for(int i=index+1;i<=right;i++){
            if(chars[i]==chars[i-1])
                continue;
            chars[index]= chars[i];
            chars[i] = temp;
            result.add(new String(chars));
            chars[i]=chars[index];
            chars[index]=temp;
        }
        return result;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务