import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* 输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入abc,它的组合有a、b、c、ab、ac、bc、abc,组合中不能出现重复的字符。
*
* @author Tang
*
*/
public class Test {
public static void main(String[] args) {
List list = getResultList("12345");
System.out.println(list);
}
public static List getResultList(String s) {
HashSet set = new HashSet();
traverseCharArray(s.toCharArray(), set);
List list = new LinkedList(set);
Collections.sort(list, new Comparator() {
public int compare(String o1, String o2) {
if (o1.length() == o2.length()) {
return o1.compareToIgnoreCase(o2);
} else {
return o1.length() - o2.length();
}
}
});
return list;
}
public static void traverseCharArray(char[] chars, HashSet set) {
for (int i = 0; i < chars.length; i++) {
recursionMerge(chars[i], getOther(chars, i), set);
}
}
public static Set recursionMerge(char c, char[] chars, HashSet set) {
Set merges = new HashSet();
String merge = merge(c + "", new String(chars));
merges.add(merge);
set.add(merge);
for (int i = 0; i < chars.length; i++) {
Set mergeSet = recursionMerge(chars[i], getOther(chars, i), set);
for (String str : mergeSet) {
String merge2 = merge(c + "", str);
set.add(merge2);
merges.add(merge2);
}
}
return merges;
}
public static char[] getOther(char[] c1, int index) {
StringBuffer buffer = new StringBuffer(new String(c1));
buffer.deleteCharAt(index);
return buffer.toString().toCharArray();
}
public static String merge(String s1, String s2) {
return s1 + s2;
}
}