Friday, September 2, 2011

How to find whether two Strings are Anagrams or not


Method 1 :

Scan first one and compute sum and product of the ASCII character codes. Do the same for the other and compare the sums and products.
You are computing two different hashcodes that are position invariant and by doing a sum and a product, you are reducing a chance of a collision. 
Overflow (esp in case of product) increases the chances of collision.

Method 2 :

Just take an array of 256 length and initialize with 0.
Now,traverse string1 and just increment the value at index=ascii code of character.
Then traverse string2, and this time decrement.
At any point if time, if you get -1 then you can break.
If you dont find so, then traverse the whole array again to check if all locations are zero then they are anagram.

Method 3 :

Sort both the strings and compare with each other , if both are same then they are Anagrams else not.

No comments:

Post a Comment