Sunday, 13 July 2014

Arrays and Strings : Write a method to decide if two strings are anagrams or not.

Two strings are anagrams if both strings contain the same characters could be in different orders . For example "abcd" , "dcba" , "bcda" all are anagrams . 
In the given question we have to check whether two strings are anagrams or not 

#include<iostream.h>
#include<conio.h>
#include<cstring.h>
bool isAnagram(string s1 , string s2)
 {
   if(s1=="" || s2=="") return false ;
   if(s1.length()!=s2.length()) return false ;
   int c[256] ;
   memset(c,0,sizeof(c));
   int len = s1.length() ;
   for(int i=0;i<len;++i)
    {
      ++c[(int)s1[i]] ;
      --c[(int)s2[i]] ;
    }

    for(int i=0 ; i<256;i++)
     {
       if(c[i]!=0) return false ;

     }
    return true ;
 }
int main ()
{
  string s1 = "abcd" ;
  string s2 = "abdc" ;
  bool ans = isAnagram(s1,s2) ;
  cout<<ans ;
  getch();
}

this problem has a very simple trick all you have to do is use a buffer int array and initialize every element to 0 . Now in a loop increment the respective ascii position of character of string s1 and at the same time decrement for s2 .  If the array elements are all 0 that means they are anagrams .
That simple :)

No comments:

Post a Comment