Anagram Strings in Java
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
In Java, we can check if two strings are anagrams by comparing their character counts. If two strings have the same character count, then they are anagrams of each other.
Implementation
Here is a simple implementation of checking if two strings are anagrams in Java:
import java.util.Arrays; public class Anagram { public static boolean checkAnagram(String str1, String str2) { if (str1.length() != str2.length()) { return false; } char[] charArray1 = str1.toCharArray(); char[] charArray2 = str2.toCharArray(); Arrays.sort(charArray1); Arrays.sort(charArray2); return Arrays.equals(charArray1, charArray2); } public static void main(String[] args) { String str1 = "listen"; String str2 = "silent"; if (checkAnagram(str1, str2)) { System.out.println("The strings are anagrams."); } else { System.out.println("The strings are not anagrams."); } } }
In this implementation, we first check if the lengths of the two strings are equal. If they are not, then they can’t be anagrams. We then convert both strings to character arrays and sort them. Finally, we use the Arrays.equals() method to compare the two sorted arrays.
Conclusion
Checking if two strings are anagrams in Java can be done by comparing their character counts. This simple implementation provides a way to determine if two strings are anagrams of each other.
🎉