package cn.android.exam;
import java.util.Arrays;
import java.util.LinkedList;
/**
* 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如:原始字符串是"abc",打印得到下列所有组合情况: "a" "b" "c"
* "ab" "bc" "ca" "ba" "cb" "ac" "abc" "acb" "bac" "bca" "cab" "cba"
*
* @author dell
*
*/
public class JavaTest {
static int count = 0;
static String str = "abc"; // 初始化一个字符
static char[] array = str.toCharArray();// 将改字符变为字符数组
static LinkedList<char[]> list = new LinkedList<char[]>();// 声明一个链表
static int[] indexs = new int[str.length()];// 声明整型数组
static int len = array.length;// 求出数组长度
public static void main(String[] args) {
getSub();
for (char[] cs : list) {
System.out.println(Arrays.toString(cs));
}
}
private static LinkedList<char[]> getSub() {
while (count <= len) {
recursionSub(0, -1);
count++;
}
return list;
}
private static LinkedList<char[]> recursionSub(int ind, int start) {
start++;
if (start > count - 1) {
return null;
}
for (indexs[start] = 0; indexs[start] < len; indexs[start]++) {
recursionSub(0, start);
if (start == count - 1) {
char[] temp = new char[count];
for (int i = count - 1; i >= 0; i--) {
temp[start - i] = array[indexs[start - i]];
}
boolean flag = true;
for (int i = 0; i < temp.length; i++) {
for (int j = i + 1; j < temp.length; j++) {
if (temp[i] == temp[j]) {
flag = false;
break;
}
}
}
if (flag) {
list.add(temp);
}
}
}
return list;
}
}
|
|