import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
/*
* 输入abc
* 输出 a b c ab ac bc
* **/
public class Test {
private static StringBuilder builder = new StringBuilder();
public static void main(String[] args) {
System.out.print("请输入字符串:");
String s = new Scanner(System.in).nextLine().trim();
Set<String> strings =countCombinations(s);
int i=0;
for(String ss:strings){
System.out.print(ss+"\t");
if(++i%5==0){
System.out.println();
}
}
}
public static Set<String> countCombinations(String s) {
List<String> indexs = calculateAllPossibleCombination(s.length());
Set<String> set = new HashSet<String>();
String temp = null;
char[] chars = null;
for (int i = 0; i < indexs.size(); i++) {
builder.setLength(0);
for (int j = 0; j < (temp = indexs.get(i)).length(); j++) {
if (temp.charAt(j) == '1') {
builder.append(s.charAt(j));
}
}
chars = builder.toString().toCharArray();
Arrays.sort(chars);
set.add(new String(chars));
}
return set;
}
private static List<String> calculateAllPossibleCombination(int length) {
List<String> strings = new ArrayList<String>();
builder.setLength(0);
for (int i = 1; i < 2 << (length - 1); i++) {
builder = new StringBuilder(Integer.toBinaryString(i));
while (builder.length() < length)
builder.insert(0, "0");
strings.add(builder.toString());
}
return strings;
}
}
输出字符串
最新推荐文章于 2021-08-21 16:02:50 发布