日期:2014-05-20  浏览次数:20574 次

问一个简单的算法问题
有这么两个字符串数组
String strA = {"h","k","i", "e"}
String strB = {"a","b","c","d","e","f","g","h","i","j","k"}

现在我要找出strA和strB的交集并输出,请问要怎么做?
如果按照这种方法效率肯定不高,要怎样改进?
Java code

for(String str1 : strA)
{
    for(String str2 : strB)
    {
        if(str1.equals(str2))
           ....
    }
}



------解决方案--------------------
用集合吧
Java code
String[] strA = {"h","k","i", "e"};
String[] strB = {"a","b","c","d","e","f","g","h","i","j","k"};
List<String> l1 = new ArrayList<String>(Arrays.asLit(strA));
List<String> l2 = new ArrayList<String>(Arrays.asLit(strB));
l1.retainAll(l2); //交集 l1.removeAll(l2)差集 l1.addAll(l2)并集
String[] sab = l1.toArray(new String[0]);
for (String s : sab) {
    System.out.println(s);
}