In the world of programming, string manipulation is a common task. One interesting challenge is determining whether two strings are anagrams of each other. 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 this post, we'll explore how to implement an anagram checker in Java, providing a clear, efficient solution.
What Is an Anagram?
An anagram occurs when two strings can be rearranged to form each other. For example:
- “listen” and “silent” are anagrams.
- “triangle” and “integral” are also anagrams.
Why Is It Important?
Understanding how to check for anagrams is beneficial in various applications, including cryptography, text processing, and games involving wordplay.
How to Check for Anagrams in Java
To determine if two strings are anagrams, we can follow these steps:
- Check Length: If the strings are of different lengths, they cannot be anagrams.
- Count Characters: Use a
HashMapto count the occurrences of each character in one string and decrement the count for characters found in the other string.
- Verify Counts: If all counts return to zero, the strings are anagrams.
Java Implementation
Here's a complete Java program to check if two strings are anagrams:
import java.util.HashMap;
import java.util.Map;
public class AnagramStrings {
public static void main(String[] args) throws Exception {
String s1 = "aabbcc";
String s2 = "cbcaab";
boolean isAnagram = checkAnagram(s1, s2);
if (isAnagram) {
System.out.println("Given strings are Anagram!");
}
else {
System.out.println("Given strings are not Anagram!");
}
}
private static boolean checkAnagram(String s1, String s2) throws Exception {
if (s1.isEmpty() || s2.isEmpty()) {
throw new Exception("Either s1 or s2 is an empty string!");
}
char[] a = s1.toCharArray().length>s2.length()?
s1.toCharArray():s2.toCharArray();
char[] b = s1.toCharArray().length<s2.length()? s1.toCharArray():s2.toCharArray();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (char c : a) {
if (map.containsKey(c)) {
map.put(c, map.get(c)+1);
}
else {
map.put(c, 1);
}
}
for (char d : b) {
if (map.containsKey(d)) {
map.put(d, map.get(d)-1);
if (map.get(d)==0) {
map.remove(d);
}
}
}
return map.isEmpty();
}
Length Check: The function first checks if the lengths of the two strings are equal. If they aren’t, it returns Character Counting: It uses a Validation: As it iterates through the second string, it decreases the count for each character found. If a character isn’t found or if any count is left non-zero, it concludes that the strings aren’t anagrams.
Anagrams are words formed by rearranging letters. Length checks are essential for efficient validation. Using
char[] b = s1.toCharArray().length<s2.length()? s1.toCharArray():s2.toCharArray();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (char c : a) {
if (map.containsKey(c)) {
map.put(c, map.get(c)+1);
}
else {
map.put(c, 1);
}
}
for (char d : b) {
if (map.containsKey(d)) {
map.put(d, map.get(d)-1);
if (map.get(d)==0) {
map.remove(d);
}
}
}
return map.isEmpty();
}
}
Explanation of the Code
false.HashMap to store character frequencies for the first string.Conclusion
Checking if two strings are anagrams is a straightforward problem that can be efficiently solved using Java. By leveraging data structures like HashMap, we can keep track of character occurrences and quickly determine if the strings can be rearranged into each other.
Key Takeaways:
HashMap simplifies character counting and verification.
Post a Comment