Java中两个字符串的交集

Dee*_*pak 15 java algorithm intersection

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

例:

String s1 = new String("Sychelless");
String s2 = new String("Sydney");
Run Code Online (Sandbox Code Playgroud)

Mat*_*hen 23

使用HashSet<Character>:

HashSet<Character> h1 = new HashSet<Character>(), h2 = new HashSet<Character>();
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]);
Run Code Online (Sandbox Code Playgroud)

这是O(m + n)渐近最优的.

  • `m`和`n`是字符串的长度.添加,删除和检查HashSet项都是O(1).所以它基本上是m(加)+ n(加)+ m(对h1中的每个元素进行一次检查)+ m(最多m次删除)+ m(转换为字符数组).所以这是4m + n,即O(m + n)(常数下降).O是大O.渐近最优意味着没有更小的大O的算法. (13认同)
  • "O(m + n)"内容用于分析算法的时间和空间要求.请参阅:http://en.wikipedia.org/wiki/Big_O_notation (2认同)

sau*_*ata 8

提取字符

String.toCharArray
Run Code Online (Sandbox Code Playgroud)

将它们放入Set Set the intersection中

Set.retainAll
Run Code Online (Sandbox Code Playgroud)


Jig*_*shi 5

最基本的方法:

String wordA = "Sychelless";  
String wordB = "Sydney";  
String common = "";  

for(int i=0;i<wordA.length();i++){  
    for(int j=0;j<wordB.length();j++){  
        if(wordA.charAt(i)==wordB.charAt(j)){  
            common += wordA.charAt(i)+" ";  
            break;
        }  
    }  
}  
System.out.println("common is: "+common);  
Run Code Online (Sandbox Code Playgroud)

  • 由于嵌套循环,这是"O(m*n)".另外,你可以使用`StringBuilder`轻松地使String创建更高效​​,因为你提前知道了大小的上限.Rasmus也是正确的,交集应该是一个集合(没有重复). (2认同)