Java Anagrams

  • + 0 comments

    static boolean isAnagram(String a, String b) {

    1. //Checking two strings lengths

      if(a.length()!=b.length()) 
      {
                  return false;
      }
      

      2.//Converting the string of characters into Uppercase (we can use Lowercase too)

      a=a.toUpperCase();        
      b=b.toUpperCase();
      

    3.//converting strings into Character Array

        char [] ch1=a.toCharArray();
        char [] ch2=b.toCharArray();
    

    4.//Sorting two Character Arrays

        char temp;
        for(int i=0;i<=ch1.length-1;i++)
        {
            for(int j=i+1;j<=ch1.length-1;j++)
            {
                if(ch1[i]>ch1[j])
                {
                    temp=ch1[i];
                    ch1[i]=ch1[j];
                    ch1[j]=temp;
                }
                if(ch2[i]>ch2[j])
                {
                    temp=ch2[i];
                    ch2[i]=ch2[j];
                    ch2[j]=temp;
                }
            }
        }
    
    1. //Checking the two Arrays character by character

      for(int i=0;i<=ch1.length-1;i++) { if(ch1[i]!=ch2[i]) { return false; } } return true;

      }