Monday, April 14, 2014

Find whether two strings are anagrams of each other or not

Given a two strings, find whether they are anagrams of each other or not.

Anagram means, rearranging of the characters in the string.

Ex:
mary and army are anagrams.
abba and abab are anagrams
abba and abbb are not anagrams



Answer:

Assumption: The characters are ASCII characters

AreAnagrams(char a[], char b[])
{
   int count[128];
   int n=strlen(a);

   if(n!=strlen(b))
      return false;

   for(int i=0; i<127; i++)
      count[i]=0;
   
   for(int i=0; i<n; i++)
      count[a[i]]++;
   for(int i=0; i<n; i++)
      count[b[i]]--;

   for(int i=0; i<127; i++)
      if(count[i]!=0)
         return false;

   return true;
}

No comments:

Post a Comment