Monday 8 August 2016

Anagrams : Check if two input strings are anagrams of each other

Anagrams are those pair of Strings which have the same set of characters , in any order

For Example :

Mad, Dam
Madam Curie = Radium came
Dog, God


Anagram: Wiki


Problem : Given two input strings s1, s2 , check wether they are anagrams of each other

Solution 

  • Create two  int arrays of size 256 , each holding count of the ascii characters present in s1 and s2 respectively
  • [ You will need to convert each letter to lower case before adding count]
  • Compare count arrays


Implementation : 




public static Boolean  isAnagram(String s1, String s2){
              int count1[] = new int[256];
              int count2[]= new int[256];


              Boolean flag= true;

              for(int i=0;i<s1.length();i++){
                   Character c= s1.charAt(i);
                   count1[Character.toLowerCase(c)]++;
             }
             for(int i=0;i<s2.length();i++){
                   Character c= s2.charAt(i);
                   count2[Character.toLowerCase(c)]++;
             }
             for(int i=0;i<256;i++){
                   if(count1[i]!=count2[i]) flag=false;
             }


      return flag;
}


No comments:

Post a Comment