Java中两个字符串的交集

需要一个Java函数来查找两个字符串的交集。 即字符串共有的字符。

例:

String s1 = new String("Sychelless"); String s2 = new String("Sydney"); 

使用HashSet

 HashSet h1 = new HashSet(), h2 = new HashSet(); for(int i = 0; i < s1.length(); i++) { h1.add(s1.charAt(i)); } for(int i = 0; i < s2.length(); i++) { h2.add(s2.charAt(i)); } h1.retainAll(h2); Character[] res = h1.toArray(new Character[0]); 

这是O(m + n) ,它是渐近最优的。

提取字符

 String.toCharArray 

将它们放入Set Find the intersection中

 Set.retainAll 

最基本的方法:

 String wordA = "Sychelless"; String wordB = "Sydney"; String common = ""; for(int i=0;i 

关于saugata的回应的更多细节(在我写这篇文章时出现): –

 public static void main(String[] args) { String s1 = "Seychelles"; String s2 = "Sydney"; Set ss1 = toSet(s1); ss1.retainAll(toSet(s2)); System.out.println(ss1); } public static Set toSet(String s) { Set ss = new HashSet(s.length()); for (char c : s.toCharArray()) ss.add(Character.valueOf(c)); return ss; } 

我认为你正在寻找的算法是最长公共子序列的问题

在这里找到同样的问题,请参考

实现一个高效的算法来找到两个字符串的交集

通过番石榴这个任务似乎更容易:

 String s1 = new String("Sychelless"); String s2 = new String("Sydney"); Set setA = Sets.newHashSet(Splitter.fixedLength(1).split(s1)); Set setB = Sets.newHashSet(Splitter.fixedLength(1).split(s2)); Sets.intersection(setA, setB); 

我使用过TreeSet 。 并在TreeSet retainAll()来获取匹配的元素。

Oracle Doc:

 retainAll(Collection c) 

仅保留此集合中包含在指定集合中的元素(可选操作)。

 String s1 = new String("Sychelless"); String s2 = new String("Sydney"); Set firstSet = new TreeSet(); for(int i = 0; i < s1.length(); i++) { firstSet.add(s1.charAt(i)); } Set anotherSet = new TreeSet(); for(int i = 0; i < s2.length(); i++) { anotherSet.add(s2.charAt(i)); } firstSet.retainAll(anotherSet); System.out.println("Matched characters are " + firstSet.toString());//print common strings //output > Matched characters are [S, e, y] 
 s1.contains(s2) returns true; s1.indexOf(s2) returns 0. s1.indexOf("foo") returns -1 

对于更复杂的案例,请使用类Pattern。