I want to find the first repeated character from a string. I usually do it using array_intersect
in php. Is there something similar in Java?
For example:
String a=zxcvbnmz
Desired output : z
I want to find the first repeated character from a string. I usually do it using array_intersect
in php. Is there something similar in Java?
For example:
String a=zxcvbnmz
Desired output : z
array_intersect — Computes the intersection of arrays (source)
So in this case you can use 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));
Output
[2, 4, 5]
You can read about this here Java, find intersection of two arrays
There's no default implementation for this behavior; however, you can code your own solution! Since you want to find the first repeated character, you can make a HashSet
of Character
s. As you iterate through the array, you add each character to the HashSet
until you come across a character already in the HashSet
- this must be the first repeated character. Example code below:
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;
}
This runs in O(n) time, as HashSet
lookups run in O(1) time.