编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符例如:原始字符串是"abc",打印得到下列所有组合情况"a" "b" "c" "ab" "bc" "ca" "ba" "cb" "ac""abc" "acb" "bac" "bca" "cab" "cba"
一开始没思路,苦思冥想一天,脑袋顿开,可以把它想象成数学中的(a+b+c)(a+b+c),下面是我的代码,你有不同的方法吗?
- package com.itheima;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Collections;
- import java.util.List;
- public class Test7 {
- public static void main(String[] args) {
- String string="abcd";
- //将字符串转换成字符数组,再将字符数组,转化成只有一个字符组成的字符串的字符串数组,转化结果是这种形式{"a","b","c","d"}
- char[]chars=string.toCharArray();
- String[] strings =new String[chars.length];
- for(int i=0;i<chars.length;i++){
- strings[i]=chars[i]+"";
- }
- // 空list
- List<String> oldList = new ArrayList<String>();
- List<String> newList = new ArrayList<String>();
- for (int i = 0; i < strings.length; i++) {
- // 装入newList,清空oldList
- for (int j = 0; j < strings.length; j++) {
- if (oldList.size() != 0) {
- for (String str : oldList) {
- //判断字符串是否含有相同字符
- if (method(strings, strings[j] + str)) {
- newList.add(strings[j] + str);
- System.out.print(strings[j] + str + " ");
- }
- }
- } else {
- newList.add(strings[j]);
- System.out.print(strings[j] + " ");
- }
- }
- System.out.println();
- oldList.clear();
- // 装入oldList,清空newList
- for (String str : newList) {
- oldList.add(str);
- }
- newList.clear();
- }
- }
- //定义一个判断字符串中是否有重复的制定的字符的方法
- private static boolean method(String[] strings, String str) {
- for (int i = 0; i < strings.length; i++) {
- int num = 0;
- char c[] = str.toCharArray();
- for (int j = 0; j < c.length; j++) {
- if ((c[j] + "") .equals(strings[i]))
- num++;
- }
- if (num > 1)
- return false;
- }
- return true;
- }
- }
复制代码 |