Count the no of common characters presented in an array of strings

Write a program that gives count of common characters presented in an array of strings..(or array of character arrays)

For eg.. for the following input strings..

aghkafgklt
dfghako
qwemnaarkf

The output should be 3. because the characters a, f and k are present in all 3 strings.



public class StringHandler {

    public static void main(String[] args) {

        String[] strings = {"aghkafgklt", "dfghako", "qwemnaarkf"};
        Set commonChars = new HashSet(convertStringAsCharSet(strings[0]));
        for (int index = 1; index < strings.length; index++) {
            commonChars.retainAll(convertStringAsCharSet(strings[index]));
        }
        System.out.println("Common characters are" + commonChars);
        System.out.println("Total number of Common characters are " + commonChars.size());

    }

    private static Set convertStringAsCharSet(String str) {

        char[] chars = str.toCharArray();
        Set charSet = new HashSet();
        for (Character character : chars) {
            charSet.add(character);
        }
        return charSet;
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s