package com.heima.test;
public class Test3 {
public static void main(String[] args) {
/*
题目:
编程列出一个字符串的全部字符组合情况。原始字符串中没有重复字符。
例如:
原始字符串是“abc”,打印得到下列所有组合情况:
“a” “b” “c”
"ab" "ac" "ba" "bc" "ca" "cb"
"abc" "acb" "bac" "bca" "cab" "cba"
*思路:
*1,发现组合的最小长度是单个字符,且就是原始字符串的每个字符,而最长长度则和字符串一样
*2,每行新组合都是在前一行旧组合的基础上,将每个旧组合与原始字符串中每个不同字符单独组合一次,获得新组合
*3,新一行组合有多少个,无法马上确定,因为都是字符串,
* 所以可以先用StringBuilder接收每个新组合,最后再切割获得每个新组合
* */
show("abc");
}
public static void show(String str) {
char[] chs = str.toCharArray();
String[] strs = chsToStrs(chs);
printString(strs);
for(int x = 2;x<str.length();x++) {
strs = addChar(chs,strs);
printString(strs);
}
}
public static String[] addChar(char[] chs,String[] oldStrs) {
StringBuilder sb = new StringBuilder();
String[] newstrs = null;
for(int x = 0;x<oldStrs.length;x++) {
for(int y = 0;y<chs.length;y++) {
if(oldStrs[x].indexOf(chs[y])>=0) {
continue;
}
String s = oldStrs[x]+chs[y];
sb.append(s).append(",");
}
}
newstrs = sb.deleteCharAt(sb.length()-1).toString().split(",");
return newstrs;
}
public static void printString(String[] strs) {
for(String s :strs) {
System.out.print("\""+s+"\"");
}
System.out.println();
}
public static String[] chsToStrs(char[] chs) {
String[] strs = new String[chs.length];
for(int x = 0;x<chs.length;x++) {
strs[x] = chs[x]+"";
}
return strs;
}
}
|
|