Tuesday, 21 August 2018

Print repeated characters of String in Java Program ?


Print repeated characters of String in Java Program ?
The standard method to tackle this issue is to get the character cluster from String, repeat through that and fabricate a Map with character and their check. At that point repeat through that Map and print characters which have seemed more than once. So you really require two circles to carry out the activity, the primary circle to construct the guide and second circle to print characters and checks.

Straightforward Solution: The arrangement is to run two settled circles. Begin crossing from left side. For each character, check in the event that it rehashes or not. In the event that the character rehashes, increase tally of rehashing characters. At the point when the check progresses toward becoming k, restore the character.
// Java program to find the first
// repeated character in a string
import java.util.*;

class Main
{
    // This function prints the first repeated
    // character in str[]
    static char firstRepeating(char str[])
    {
        // Creates an empty hashset
        HashSet<Character> h = new HashSet<>();

        // Traverse the input array from left to right
        for (int i=0; i<=str.length-1; i++)
        {
            char c = str[i];

            // If element is already in hash set, update x
            // and then break
            if (h.contains(c))
                return c;

            else // Else add element to hash set
                h.add(c);
        }

        return '\0';
    }

    // Driver method to test above method
    public static void main (String[] args)
    {
        String str = "internationalyouthacuity";
        char[] arr = str.toCharArray();
        System.out.println(firstRepeating(arr));
    }
}

0 comments:

Post a Comment