How to find anagrams and count the most frequent in a string array in Java

Google+ Pinterest LinkedIn Tumblr +

The first step is to create a function that compares two input strings, if those strings are an anagram the function will return true or if its not it will return false.

Let’s name our function boolean isAnagram(String string1, String string2).

Of course, if we compare those strings as they are we can’t find out if they are anagrams, so there is a need to process a little bit those string in a way that we will be able to say that they are anagrams.
Now a good way to do this is to make the strings in lower case then we will have to convert those strings into characters arrays and last to sort them out.

This way the characters arrays will contain the same characters but in an order, so if str2 is an anagram of str1 they will have the same size and the same characters in the same order.
Take a look at the code below:

The second step is to create a function that will make use of the function isAnagram and count the most frequent one, the total anagrams and the number of unique strings in the input String array and return those values in an array. Let’s name this method int[] mostCommonAnagram(String[] strArray).

In this method we are going to compare each string with the rest of the elements of the input string array. If the function isAnagram return true then we have a match to count, also we must keep count for the number of matches for every different anagram, we will use the variable score for that purpose. If another anagram achieves higher score then we will know it.

Here is the code:

Note: At the end i increase the values of totalmatchings and numOfMostFr by 1.

In the main method you can put any number of anagrams in the array as input in the int[] mostCommonAnagram(String []strArray) and display the results.

When executed it prints the following results:

Below you can find the full source code of the example.

 

Share.

Leave A Reply