Java Anagrams

  • + 22 comments

    In this ,I am returning false in starting if the string length is not same. Now, when they are of same length, then I am simply taking two int arrays of size 26 (total number of alphabets), where each index represents the location of each alphabets. For example, 0-'A', 1-'B',......upto..,25-'Z'. Then i am making the whole string in uppercase to avoid Case sensitivity. Now i am traversing both the strings of equal length with a single loop and doing this simple operation:

    " character at ith position of string - 'A' ". This gives me the supposed index location of each character in array.

    For ex: if charAt(i) is 'A', then, 'A' - 'A' = 0, similarly, for B, 'B' - 'A' = 1.......upto...'Z' - 'A ' =25..Thus i get the indexes of the characters , and I increment the value of that index on each occurance of the character, which was initially 0.

    Note: Array 'c' represents Occurances of each elements in string 'a', and array 'd' is for string 'b'.

    Now we compare the occurances of each character in both the arrays. If any occurance is not equal then we return False. When all the occurances were same and for loop terminates , then we reutrn True.