- /**
- *
- *
- * 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如:
- 原始字符串是"abc",打印得到下列所有组合情况:
- "a" "b" "c"
- "ab" "bc" "ca" "ba" "cb" "ac"
- "abc" "acb" "bac" "bca" "cab" "cba"
- * @author lwh
- *
- */
- class Test{
- public static void main(String[] args) {
- StringBuilder str = new StringBuilder("abc");
- Set<String> set = new TreeSet<String>();
- char[] ch = str.toString().toCharArray();
- print(ch, new StringBuilder(), set, 0);
- System.out.println();
- System.out.println("----------------");
- Set<String> set2 = quChongFu(set);
- Iterator<String> it2 = set2.iterator();
- while (it2.hasNext()) {
- System.out.print(it2.next() + " ");
- }
- }
- // 去掉集合中重复的元素
- /*
- * set:需要除去重复字符元素的集合
- */
- public static Set<String> quChongFu(Set<String> set) {
- Set<String> set2 = new TreeSet<String>();
- Map<Character, Integer> map = null;
- Iterator<String> it2 = set.iterator();
- int count;
- while (it2.hasNext()) {
- map = new HashMap<Character, Integer>();
- count = 1;
- boolean flag = false;
- String str = it2.next();
- char[] ch = str.toCharArray();
- for (int i = 0; i < ch.length; i++) {
- if (!map.containsKey(ch[i])) {
- count = 1;
- map.put(ch[i], count);
- }
- if (map.containsKey(ch[i])) {
- map.put(ch[i], count);
- count++;
- }
- }
- // System.out.println(map);
- for (int j = 0; j < ch.length; j++) {
- if (map.get(ch[j]) > 1) {
- flag = false;
- // System.out.println("r");
- break;
- } else
- flag = true;
- }
- if (flag) {
- // System.out.println("s");
- set2.add(str);
- }
- }
- // System.out.println(set2);
- return set2;
- }
- // 利用递归打印所有组合
- /*
- * ch:需要打印在组合的字符数组
- * subStr:子字符串缓存,每个组合临时保存的变量
- * set:最后存入的集合
- * cout:递归的层数,和ch参数的(长度)相等
- */
- public static void print(char[] ch, StringBuilder subStr, Set<String> set,
- int count) {
- // 递归一层自加一次
- count++;
- // 当递归层数大于字符数组长度时退出
- if (count > ch.length) {
- return;
- }
- for (int i = 0; i < ch.length; i++) {
- // 当前字符添加到缓存变量中
- subStr.append(ch[i]);
- // 打印所有组合,包括重复的
- System.out.print(subStr.toString() + ",");
- // 将缓存变量中的数据转换成字符串存入集合中
- set.add(subStr.toString());
- // 进入下一层,也就是字符数组的下一个字符
- print(ch, subStr, set, count);
- // 删除上次保存的最后一个字符,避免了字符重复
- subStr.deleteCharAt(subStr.length() - 1);
- }
- }
- }
复制代码
|