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
2
  • What do you actually need to get those values for? Maybe we can answer that question. Commented May 12, 2017 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? Commented May 12, 2017 at 12:41

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ive upvoted sir. This is totally legit. Idk why its downvoted
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.