题目
给定一个字符串的集合,格式如:{aaa bbb ccc}, {bbb ddd},
{eee fff},{ggg},{ddd hhh},将其中交集不为空的集合合并,要
求合并完成后的集合之间无交集。例如上例应输出{aaa bbb ccc
ddd hhh}, {eee fff}, {ggg}
代码语言:javascript复制import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Demo17
{
public Demo17 (){}
public static void main(String[] args)
{
Map map = new HashMap();//用于统计重复的 set在list中的 角标
List> al = new ArrayList>();//用于存放set
List> al2 = new ArrayList>();//用于存放set中含有交集的 set
List> al3 = new ArrayList>();//用于存放将有交集的合并后 存放在此set中
HashSet list_last = new HashSet();//将有交集的 存放在此set中
Set s1 = new HashSet();
s1.add("aaa");
s1.add("bbb");
s1.add("ccc");
Set s2 = new HashSet();
s2.add("bbb");
s2.add("ddd");
Set s3 = new HashSet();
s3.add("eee");
s3.add("fff");
Set s4= new HashSet();
s4.add("ggg");
Set s5 = new HashSet();
s5.add("ddd");
s5.add("hhh");
al.add((HashSet) s1);
al.add((HashSet) s2);
al.add((HashSet) s3);
al.add((HashSet) s4);
al.add((HashSet) s5);
map = getResult(al);
merge(map, al, al2, al3, list_last);
al.removeAll(al2);
al.addAll(0,al3);
printList(al);
}
private static List> merge(Map map,List> al,List> al2,List> al3,HashSet list_last)
{
Set keyset = map.keySet();
int key1 = -1;
int key2 = 0;
Iterator it = keyset.iterator();
while(it.hasNext())
{
key1=key2;
key2 = it.next();
int value = map.get(key2);
if(!list_last.isEmpty())
{
list_last = new HashSet();
}
if(key1!=-1&&key2==map.get(key1))
{
list_last.addAll(al.get(key2));
list_last.addAll(al.get(value));
al2.add(al.get(key2));
al2.add(al.get(value));
if(al3.size()-1>=0)
{
al3.get(al3.size()-1).addAll(list_last);
}
else
{ al3.add(list_last);
}
}else
{
list_last.addAll(al.get(key2));
list_last.addAll(al.get(value));
al2.add(al.get(key2));
al2.add(al.get(value));
al3.add(list_last);
}
}
return al;
}
private static Map getResult( List> al)
{
Map map = new HashMap();
String str=null;
// HashSet[] s = (HashSet [])al.toArray();
System.out.println(al.size());
HashSet[] s = new HashSet[al.size()] ;
al.toArray(s);
for (int i=0;i it2 = s[j].iterator();
while(it2.hasNext())
{
str= it2.next();
if(s[i].contains(str))
{
map.put(i,j);
System.out.println(map);
break;
}
}
}
}
return map;
}
private static void printList(List> al)
{
Iterator > it = al.iterator();
while(it.hasNext())
{
HashSet s = it.next();
String [] sarr =new String [s.size()];
s.toArray(sarr);
System.out.print("{");
for (int i = 0; i < sarr.length; i )
{
if(i!=sarr.length-1)
System.out.print(sarr[i] ",");
else
System.out.print(sarr[i]);
}
System.out.print("}");
}
}
}