Tuesday 20 August 2013

Write a method to determine if two strings are anagrams of each other

Write a method to determine if two strings are anagrams of each other.

e.g. isAnagram(“secure”, “rescue”) → true
e.g. isAnagram(“conifers”, “fircones”) → true 
e.g. isAnagram(“google”, “facebook”) → false


Solution:

boolean isAnagram(String str, String str2){
      if(str == null && str2 == null)
             return true;

      if(str == null || str2 == null)
             return false;

      if(str.length() != str2.length())
             return false;

      int []count = new int[256];

      //count the occurrence of characters in given string "str".   
      for(int i = 0; i < str.length(); i++){
            int c = str.charAt(i);
            count[c]++;
      } 
     
     for(int i = 0; i < str2.length(); i++){
             int ch = str2.charAt(i);
             if(--count[ch] < 0)
                   return false;
     }  
     return true;  
}


No comments:

Post a Comment