Two strings are anagrams if they are permutations of each other. Assuming we have an ASCII alphabet we can take 128 integer array to count the characters in the first string. Then decrement the count for the corresponding character in the second string. If all the character counts are zero then the strings are anagrams else they are not.
public class anagrams {
public static boolean anagramsHelper(String[] words)
{
for(int i = 1 ; i < words.length ; i++)
{
if(!areAnagrams(words[0], words[i]))
{
return false;
}
}
return true;
}
public static boolean areAnagrams(String word1, String word2)
{
if(word1.length() != word2.length())
{
return false; // anagrams are strings with same length
}
int[] charCount = new int[128]; // 128 unique chars in ASCII
//count the chars in word1
for(int i = 0 ; i < word1.length() ; i++)
{
charCount[(int)word1.charAt(i)]++;
}
//decrement the char count for chars in word2
for(int i = 0 ; i < word2.length() ; i++)
{
if(charCount[(int)word2.charAt(i)] == 0)
{
return false;
}
charCount[(int)word2.charAt(i)]--;
}
//verify if any char count is non zero
//for anagrams it should be zero else they are not anagrams
for(int i = 0 ; i < 128 ; i++)
{
if(charCount[i] != 0)
{
return false;
}
}
return true;
}
public static void main(String[] args) {
String[] words = {"abc", "bca", "cab" , "myd"};
System.out.println(anagramsHelper(words));
}
}