在Java中的两个字符串的交集字符串、两个、Java

由网友(犯错只因失恋太少)分享简介:需要一个Java功能,找到两个字符串的交集。即,常见到的字符串的字符。例如:字符串S1 =新的String(Sychelless);字符串s2 =新的String(悉尼);解决方案 使用的HashSet<性格> :的HashSet<性格> H1 =新的HashSet<性格>(),H...

需要一个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),这是渐近最优的。

Java开发技术之字符串String类的特点

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.

阅读全文

相关推荐

最新文章