在Java中的两个字符串的交集 [英] Intersection of two strings in Java
本文介绍了在Java中的两个字符串的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要一个Java功能,找到两个字符串的交集。即,常见到的字符串的字符。
例如:
字符串S1 =新的String(Sychelless);
字符串s2 =新的String(悉尼);
解决方案
使用的HashSet<性格>
:
的HashSet<性格> H1 =新的HashSet<性格>(),H2 =新的HashSet<性格>();
的for(int i = 0; I< s1.length();我++)
{
h1.add(s1.charAt(ⅰ));
}
的for(int i = 0; I< s2.length();我++)
{
h2.add(s2.charAt(ⅰ));
}
h1.retainAll(H2);
字[] RES = h1.toArray(新字[0]);
这是 O(M + N)
,这是渐近最优的。
Need a Java function to find intersection of two strings. i.e. characters common to the strings.
Example:
String s1 = new String("Sychelless");
String s2 = new String("Sydney");
解决方案
Using 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]);
This is O(m + n)
, which is asymptotically optimal.
这篇关于在Java中的两个字符串的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文