Any word or phrase that exactly reproduces the letters in another order is an anagram.
Example: cat – act, study – dusty, gainly – laying etc.,
Logic for anagram is below:
- Check for same length
- Sort the letters in the given word
- Compare the sorted words are same
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Arrays; public class Anagram { public static void main(String[] args) { System.out.println(" Is cat,act Anagram: " + isAnagram("cat", "act")); System.out.println(" Is study,dusty Anagram: " + isAnagram("study", "dusty")); System.out.println(" Is gainly,laying Anagram: " + isAnagram("gainly", "laying")); } public static boolean isAnagram(String inputStr1, String inputStr2) { if(inputStr1==null || inputStr2 == null || (inputStr1.length()!=inputStr2.length())) { return false; } char[] letters1 = inputStr1.toUpperCase().toCharArray(); char[] letters2 = inputStr2.toUpperCase().toCharArray(); Arrays.sort(letters1); Arrays.sort(letters2); return Arrays.equals(letters1, letters2); } } |
Output:
1 2 3 4 |
Is cat,act Anagram: true Is study,dusty Anagram: true Is gainly,laying Anagram: true |