今天写的可以参考下
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeSet;
- class ForTest3 {
- public static void main(String[] args) {
- StringBuffer str = new StringBuffer("abc");
- Set<String> set = new TreeSet<String>();
- char[] ch = str.toString().toCharArray();
- print(ch, new StringBuffer(), 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:需要打印在组合的字符数组
- * str:子字符串缓存,每个组合临时保存的变量
- * set:最后存入的集合
- * cout:递归的层数,和ch参数的(长度)相等
- */
- public static void print(char[] ch, StringBuffer str, Set<String> set,
- int count) {
- //递归一层自加一次
- count++;
- //当递归层数大于字符数组长度时退出
- if (count > ch.length) {
- return;
- }
- for (int i = 0; i < ch.length; i++) {
- //当前字符添加到缓存变量中
- str.append(ch[i]);
- //打印所有组合,包括重复的
- System.out.print(str.toString() + ",");
- //将缓存变量中的数据转换成字符串存入集合中
- set.add(str.toString());
- //进入下一层,也就是字符数组的下一个字符
- print(ch, str, set, count);
- //删除上次保存的最后一个字符,避免了字符重复
- str.deleteCharAt(str.length() - 1);
- }
- }
- }
复制代码 |