- public class Test6 {
- /**
- * 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如:
- * 原始字符串是"abc",打印得到下列所有组合情况:
- * "a" "b" "c"
- * "ab" "bc" "ca" "ba" "cb" "ac"
- * "abc" "acb" "bac" "bca" "cab" "cba"
- * @param args
- */
- static int k=1;
- static class StopException extends RuntimeException{}
- public static void main(String[] args) {
- //调用print方法
- try {
- print("abc");
- } catch (StopException e) {
- }
- }
- //将字符串存储到数组中
- public static void print(String str) {
- int x = str.length();
- String[] ch1 = new String[x];
- String[] ch2 = new String[x];
- for (int i = 0; i < str.length(); i++) {
- ch1[i] = str.substring(i, i + 1);
- ch2[i] = str.substring(i, i + 1);
- }
- //输出单个字符
- for(String string:ch1) {
- System.out.print(string+" ");
- }
-
- myout(ch1, ch2);
- }
- public static void myout(String[] ch1, String[] ch2) {
- StringBuffer sbf = new StringBuffer();
- String[] ch3 = null;
-
- //控制递归的次数
- k++;
-
- for (int i = 0; i < ch1.length; i++) {
- for (int j = 0; j < ch2.length; j++) {
- if (!(ch2[j].contains(ch1[i]))) {
- String s = ch1[i] + ch2[j];
- sbf.append(s+" ");
- }
- }
- }
- // 切割字符串
- String s = sbf.toString();
- System.out.println();
- ch3 = s.split(" ");
- for (String string : ch3) {
- System.out.print(string+" ");
- }
- if (k==ch1.length) {
-
- throw new StopException();
- }
- //递归
- myout(ch1, ch3);
- }
-
- }
复制代码 |
|