我想从字符串中找到第一个重复的字符。我通常在php中使用array_intersect
。 Java中有类似的东西吗? 例如:在java中是否有array_intersect()等价物?
String a=zxcvbnmz
Desired output : z
我想从字符串中找到第一个重复的字符。我通常在php中使用array_intersect
。 Java中有类似的东西吗? 例如:在java中是否有array_intersect()等价物?
String a=zxcvbnmz
Desired output : z
array_intersect - 计算数组的交集(source)
因此,在这种情况下可以使用Set::retainAll:
Integer[] a = {1,2,3,4,5};
Integer[] b = {2,4,5,6,7,8,9};
Set<Integer> s1 = new HashSet<>(Arrays.asList(a));
Set<Integer> s2 = new HashSet<>(Arrays.asList(b));
s1.retainAll(s2);
Integer[] result = s1.toArray(new Integer[s1.size()]);
System.out.println(Arrays.toString(result));
输出
[2, 4, 5]
你可以阅读这个在这里Java, find intersection of two arrays
太棒了!这个也可以。 –
欢迎您@RedBottle –
Ive upvoted先生。这完全合法。 Idk为什么它downvoted –
有此行为的默认实现;但是,您可以编写自己的解决方案!既然你想找到第一个重复的字符,你可以制作一个HashSet
的Character
s。在遍历数组时,将每个字符添加到HashSet
,直到遇到HashSet
中已有的字符 - 这必须是第一个重复的字符。下面的实施例的代码:
public char arrayIntersect(String string) {
HashSet<Character> hashSet = new HashSet<>();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (hashSet.contains(c))
return c;
else
hashSet.add(c);
}
return null;
}
此运行在O(n)的时间,如HashSet
查找在O(1)时间运行。
thnks很多。 upvoted。 –
你实际需要什么来获得这些值?也许我们可以回答这个问题。 –
一直试图学习Java,并有这个问题显示字符串中的第一个重复的字符。这在php中相当简单。有没有可用于简化解决方案的内置功能? –