Thursday, 29 November 2012

Write a Java Program to check two string if they are anagram of each other

package AnaGram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class myAnagram
{

    public static void main(String[] args) throws IOException
    {
        // TODO code application logic her
        BufferedReader reader1= new BufferedReader(new InputStreamReader(System.in));
            System.out.println("\nEnter first string:");
            String s1= reader1.readLine();
         
        BufferedReader reader2= new BufferedReader(new InputStreamReader(System.in));
            System.out.println("\nEnter first string:");
            String s2= reader2.readLine();
     
            Anagram ana = new Anagram();
        if(ana.check(s1,s2)==true)
            System.out.println(" String "+s1+" is anagram of "+s2);
        else
            System.out.println(" String "+s1+" is not anagram of "+s2);
    }
}



class Anagram
{
    boolean check(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;
    }
}


0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top