编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如: 原始字符串是"abc",打印得到下列所有组合情况: "a" "b" "c"
* "ab" "bc" "ca" "ba" "cb" "ac" "abc" "acb" "bac" "bca" "cab" "cba"
------解决方案--------------------
public static void main(String[] args) {
String str = "abcde";
List<String> strAss = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
String sub = str.substring(i, j);
int r = 0;
while (r++ < sub.length()) {
strAss.add(sub);
sub = sub.substring(1) + sub.substring(0, 1);
}
}
}
for (String a : strAss) {
System.out.println(a);
}
}
输出:
a
ab
ba
abc
bca
cab
abcd
bcda
cdab
dabc
abcde
bcdea
cdeab
deabc
eabcd
b
bc
cb
bcd
cdb
dbc
bcde
cdeb
debc
ebcd
c
cd
dc
cde
dec
ecd
d
de
ed
e
------解决方案--------------------
public class Test0718 {没有判断重复字母,判断重复的话就要把这些放到set里,输出:
static char[] chars="abcd".toCharArray();
public static void main(String[] args) {
for(int i=0;i<chars.length;i++){
//取得每一个字符
List<Integer> list=new ArrayList<Integer>();
list.add(i);
play(list);
}
}
//使用递归,每次加上列表中不存在的一个字符
private static void play(List<Integer> list){
print(list);
for(int i=0;i<chars.length;i++){
if(!list.contains(i)){
List<Integer> temp=new ArrayList<Integer>(list);
temp.add(i);
play(temp);
}
}
}
//打印列表内容
private static void print(List<Integer> list){
for(Integer i:list)
System.out.print(chars[i]+"");
System.out.println();
}
}
a
ab
abc
abcd
abd
abdc
ac
acb
acbd
acd
acdb
ad
adb
adbc
adc
adcb
b
ba
bac
bacd
bad
badc
bc
bca
bcad
bcd
bcda
bd
bda
bdac
bdc
bdca
c
ca
cab
cabd
cad
cadb
cb
cba
cbad
cbd
cbda
cd
cda
cdab
cdb
cdba
d
da
dab
dabc
dac
dacb
db
dba
dbac
dbc
dbca
dc
dca
dcab
dcb
dcba