Saturday, March 29, 2014

java Program to find if two Strings are Anagrms



To find if two given Strings are Anagram of each other is very commonly asked interview Question.

Any word or phrase that exactly reproduces the letters in another order is an anagram.
for example "William Shakespeare " and  "I am a weakish speller " are Anagrams.

In a perfect anagram, every letter must be used, with exactly the same number of occurrences as in the anagrammed word or phrase.

Below is my code of checking if two given strings are anagrams.




public class Anagram { 
 
        boolean isAnagram(String s1,String s2) {       

           char a1[]= s1.toCharArray();
           char a2[]= s2.toCharArray();
           int []index1= new int[26];
           int []index2= new int[26];

           int i = 0;
           for(i=0;i<a1.length;i++) {
               index1[a1[i]-'a']++;
           }

           for(i=0;i<a2.length;i++) {
               index2[a2[i]-'a']++;           
           }

           for(i=0;i<26;i++) {
               if(index1[i]!=index2[i])
                     return false;
           }
           return true;
      }

      public static void main(String[] args) {
    
          String s1="xyzabc";
          String s2 = "abcxyz";

          Anagram anagram = new Anagram();

          if(anagram.isAnagram(s1,s2)==true)
               System.out.println(" String "+s1+" is anagram of "+s2);
          else
               System.out.println(" String "+s1+" is not anagram of "+s2);
      }
}

Output:
==================================================================
 String xyzabc is anagram of abcxyz


No comments :

Post a Comment