Is there an array_intersect() equivalent in java?
我想从字符串中找到第一个重复的字符。 我通常在php中使用array_intersect进行操作。 Java中有类似的东西吗?
例如:
1 2
| String a =zxcvbnmz
Desired output : z |
-
您实际上需要什么来获得这些值? 也许我们可以回答这个问题。
-
一直在尝试学习Java,并提出了这个问题来显示字符串中的第一个重复字符。 它在php中相当简单。 有没有可以用来简化解决方案的内置函数?
array_intersect —计算数组的交集(源)
因此,在这种情况下,您可以使用Set :: retainAll:
1 2 3 4 5 6 7 8
| 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 )); |
输出量
您可以在此处阅读有关Java的内容,找到两个数组的交集
-
我已经投票赞成先生。 这是完全合法的。 Idk为什么其投票率低
此行为没有默认实现; 但是,您可以编写自己的解决方案! 由于要查找第一个重复的字符,因此可以使HashSet等于Character s。 遍历数组时,将每个字符添加到HashSet中,直到遇到HashSet中已经存在的字符-这必须是第一个重复的字符。 下面的示例代码:
1 2 3 4 5 6 7 8 9 10 11 12
| 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)时间运行。