Java练习题-输入一个字符串,输出该字符串中字符的所有组合(二)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 输入一个字符串,输出该字符串中字符的所有组合,组合中不能出现重复的字符和颠倒的组合。
 * 如:
 * abc ==> a、b、c、ab、ac、bc、abc
 * abcd ==> a、b、c、d、 ab、ac、ad、bc、bd、cd、 abc、abd、acd、bcd、 abcd
 * 
 * @author tang
 *
 */
public class Test {

    public static void main(String[] args) {
        List combinations = getCombinations("abcde");
        System.out.println(combinations);
    }

    private static List getCombinations(String str) {
        List resultList = new ArrayList<>();
        char[] charArray = str.toCharArray();
        String[] source=new String[charArray.length];
        for (int i = 0; i < source.length; i++) {
            source[i]=""+charArray[i];
            resultList.add(""+charArray[i]);
        }
        List preResult=Arrays.asList(source);
        for (int len = 0; len < source.length; len++) {

            Map> map=new HashMap<>();
            for (int j = 0; j < preResult.size(); j++) {
                String k=preResult.get(j).charAt(0)+"";
                if (!map.containsKey(k)) {
                    map.put(k, new ArrayList());
                }
                map.get(k).add(preResult.get(j));
            }
            preResult=new ArrayList<>();
            for (int i = 0; i < source.length; i++) {
                List list = new ArrayList<>();
                for (int j = i+1; j < source.length; j++) {
                    List list2 = map.get(source[j]);
                    if (list2!=null) {
                        list.addAll(map.get(source[j]));
                    }
                }
                for (int j = 0; j < list.size(); j++) {
                    resultList.add("" +source[i] + list.get(j));
                    preResult.add("" +source[i] + list.get(j));
                }
            }
        }
        return resultList;
    }
}

你可能感兴趣的:(JavaSE)