How write a Java program to check if two string are anagram of each other?
Simplest algo for checking if two strings are an anagram is :
sort_by_letters(a_string)==sort_by_letters(b_string)
Example:
Words "LISTEN" and "SILENT" sorted alphabetically both equals to "EILNST".
BTW, you should learn sorting algorithms very good, because they are prerequisite to other types of algorithms for solving bunch of problems.
A few hints (another take to make you think and compare with Mark ’s suggestions. Ideally, try to implement both, that’s the best way to learn!
This is a nice exercise to think about because soo many different solutions are possible. Some will be efficient, some will be easier to code, some easier to read and understand. Trying to find different solutions to address this will help you decide which tradeoff is the best for you in this case.
If you are trying to learn, you should tell us which part you cannot figure out.
(If you are just trying to get answer for your homework, just Google and copy-paste.)
The first step should be to describe the approach for this problem in human language. For example:
For every letter, check if it is in the second word.
After doing this for all letters in the first word, are there any letters left in the second one?
Might want to just check the length at the start, then you can save some effort and won't need the last check.
After doing this in human language, it's time to convert it to Java. Post some details if you get stuck with that.
(For bonus points, note that something you may consider a letter, might not fit inside a character in Java. This may apply for Chinese characters for example. The solution will be more complex if you want to support those.)
Mark
HelgaMkt
Sort both strings and then compare the sorted strings.
import java.util.Arrays; public class AnagramSample { public static void main(String args[]) { String str1 = "recitals"; String str2 = "articles"; if (str1.length()==str2.length()) { char[] arr1 = str1.toCharArray(); Arrays.sort(arr1); System.out.println(Arrays.toString(arr1)); char[] arr2 = str2.toCharArray(); Arrays.sort(arr2); System.out.println(Arrays.toString(arr2)); System.out.println(Arrays.equals(arr1, arr2)); if(arr1.equals(arr2)) { System.out.println("Given strings are anagrams"); } else { System.out.println("Given strings are not anagrams"); } } } }