How to check if two strings are anagram of each other


Problem

How to check if two Strings are anagram of each other in java.
Anagram means two Strings which have same character but in different order.
For example:
“Same” and “Mase” are anagrams but “Same” and “Semt” are not.
There are many ways to solve the problem.

Using sort

Sort both the Strings and compare them.

Output:

If same and mase are anagrams: true
If same and semt are anagrams: false

Using array

1. Create an array of size 256 to cover all the characters.
2. For first string increment count of character in the corresponding position at count array.
3. For second string decrement the count of character in the corresponding position at count array.
4. Repeat steps 2 and 3 till we reach end of any string.
5. If array contains only 0 at the end, that means Strings are anagrams.

Output:

If same and mase are anagrams: true
If same and semt are anagrams: false

Leave a Reply

Your email address will not be published. Required fields are marked *