Monday, 30 May 2016

9. [Technical Interview] Check if two strings are anagrams in Java

You may be asked during an interview how to determine if two strings are anagrams (ie. bob, bbo, obb are anagrams).

You can create an int array that will keep count of each character see in the first string. Then iterate through each character seen in the second string. If at the end, the int array contains zero count for each character, then that means string 1 and string 2 both contains the same occurrence of each character and thus, they are anagrams!
 public class HelloWorld  
 {  
   public static boolean anagram(String first, String second)  
   {  
     // if the lengths of both strings are not the same, then they cannot  
     // be anagrams  
     if (first.length() != second.length())  
       return false;  
       
     // int array to keep count of each character  
     int[] letters = new int[256];  
       
     // increment the count of each character in the first string  
     // that we see  
     for (char c : first.toCharArray())  
     {  
       letters[c]++;  
     }  
       
     // decrement the count of each character we see in the second  
     // string  
     for (char character : second.toCharArray())  
     {  
       letters[character]--;  
     }  
       
     // check to see that each character count is zero and if so,  
     // that means the occurrence of each letter in both strings  
     // are the same, and hence they are anagrams, return false  
     // if we find a letter count that is not 0  
     for (int i : letters)  
     {  
       if (letters[i] != 0)  
         return false;  
     }  
         
     return true;  
   }  
   
    public static void main(String []args){  
     System.out.println(anagram("bob", "bbo"));  
    }  
 }  

No comments:

Post a Comment

Thank you for not blocking our ads =)

Please consider adding this blog to the whitelist of your ads blocker :)