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、ba、bc、ca、cb、abc、acb、bac、bca、cab、cba
*
* @author tang
*
*/
public class Test {
public static void main(String[] args) {
List<String> list = getResultList("12345");
System.out.println(list);
}
public static List<String> getResultList(String s) {
HashSet<String> set = new HashSet<String>();
traverseCharArray(s.toCharArray(), set);
List<String> list = new LinkedList<String>(set);
Collections.sort(list, new Comparator<String>() {
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<String> set) {
for (int i = 0; i < chars.length; i++) {
recursionMerge(chars[i], getOther(chars, i), set);
}
}
public static Set<String> recursionMerge(char c, char[] chars, HashSet<String> set) {
Set<String> merges = new HashSet<String>();
String merge = merge(c + "", new String(chars));
merges.add(merge);
set.add(merge);
for (int i = 0; i < chars.length; i++) {
Set<String> 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;
}
}
Java练习题-输入一个字符串,输出该字符串中字符的所有组合(一)
最新推荐文章于 2021-02-16 07:05:29 发布