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)渐近最优的.
提取字符
String.toCharArray
Run Code Online (Sandbox Code Playgroud)
将它们放入Set Set the intersection中
Set.retainAll
Run Code Online (Sandbox Code Playgroud)
最基本的方法:
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)