1

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Red Bottle
  • 2,839
  • 4
  • 22
  • 59
  • What do you actually need to get those values for? Maybe we can answer that question. – Steve Smith May 12 '17 at 12:39
  • Been trying to learn java and there's this question to display the first repeated character in a string. It's rather simple in php. Is there an inbuilt function I could use to simplify the solution? – Red Bottle May 12 '17 at 12:41

2 Answers2

5

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

Community
  • 1
  • 1
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
2

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 Characters. 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.

Aneesh Ashutosh
  • 762
  • 7
  • 18