gpt4 book ai didi

java - Java中两个字符串的交集

转载 作者:太空狗 更新时间:2023-10-29 23:00:56 25 4
gpt4 key购买 nike

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

示例:

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

最佳答案

使用 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]);

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

关于java - Java中两个字符串的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4448370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com