In this article, we will implement an Anagram Program in Java.
What is the concept of Anagram?
Two strings are said to be anagram of each other if they contain the same characters but in different arrangements.
For Example, below and elbow are anagram of each other as they contain the same set of characters but in different ordering.
Different approaches for developing Anagram Program in Java
We will follow the below three approaches to develop Anagram Program in Java
- Sorting Approach
- Frequency Count Approach
- HashMap Approach
Sorting Approach
Solution Steps
- Replace the spaces in the input Strings with blank.
- Obtain char Arrays from the Strings.
- Sort the char Arrays so obtained in step 2.
- Check the equality of the sorted arrays obtained in step 3.
Java Code
Let’s implement Anagram Program in Java by using sorting Approach.
package com.java.programs;
import java.util.Arrays;
public class AnagramCheck {
public static boolean isAnagram(String str1, String str2) {
char chars1[] = str1.replaceAll(" ", "").toCharArray();
char chars2[] = str2.replaceAll(" ", "").toCharArray();
Arrays.sort(chars1);
Arrays.sort(chars2);
return Arrays.equals(chars1, chars2);
}
public static void main(String[] args) {
System.out.println(isAnagram("below","elbow"));
System.out.println(isAnagram("meal for one","for me alone"));
System.out.println(isAnagram("test","java"));
System.out.println(isAnagram("Dormitory","Dirty room"));
}
}
true
true
false
true
Frequency Count Approach
Solution Steps
- Compare the lengths of the input strings, str1 and str2. If they are not equal, return false.
- Create an integer array called frequency with a size of 26, assuming lowercase English alphabets. This array will track the frequency of each character.
- Iterate over the characters of str1 and str2 simultaneously.
- For each character in str1, increment its corresponding frequency count in the frequency array.
- For each character in str2, decrement its corresponding frequency count in the frequency array.
- After the iteration, check the frequency array.
- If any element in the frequency array is non-zero, return false, indicating the frequencies of characters in str1 and str2 do not match.
- If all elements in the frequency array are zero, return true, indicating str1 and str2 are anagrams.
Java Code
Let’s implement Anagram Program in Java by using Frequency Count Approach.
public class AnagramProgram {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
boolean isAnagram = checkAnagram(str1, str2);
System.out.println("Are '" + str1 + "' and '" + str2 + "' anagrams? " + isAnagram);
}
public static boolean checkAnagram(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
int[] frequency = new int[26]; // Assuming inputs are in lowercase English alphabets
for (int i = 0; i < str1.length(); i++) {
frequency[str1.charAt(i) - 'a']++;
frequency[str2.charAt(i) - 'a']--;
}
for (int count : frequency) {
if (count != 0) {
return false;
}
}
return true;
}
}
Output
Are 'listen' and 'silent' anagrams? true
HashMap Approach
Solution Steps
- Check if the lengths of str1 and str2 are equal. If they are not equal, return false, as anagrams must have the same length.
- Create a HashMap called charFrequency to store character frequencies.
- Iterate over the characters of str1.
- For each character encountered, check if it already exists as a key in the charFrequency HashMap.
- If it does not exist, add the character as a key to charFrequency and set its value to 1.
- If it already exists, increment its corresponding value by 1.
- Iterate over the characters of str2.
- For each character encountered, check if it exists as a key in the charFrequency HashMap.
- If it does not exist, or if its corresponding value is 0, return false, as the frequencies do not match.
- If it exists, decrement its corresponding value by 1.
- After the iteration is complete, check if all values in the charFrequency HashMap are 0.
- If they are all 0, return true, indicating that str1 and str2 are anagrams.
- If any value is non-zero, return false.
Java Code
Let’s implement Anagram Program in Java by using HashMap Approach.
import java.util.HashMap;
import java.util.Map;
public class AnagramProgram {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
boolean isAnagram = checkAnagram(str1, str2);
System.out.println("Are '" + str1 + "' and '" + str2 + "' anagrams? " + isAnagram);
}
public static boolean checkAnagram(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
Map<Character, Integer> charFrequency = new HashMap<>();
for (char c : str1.toCharArray()) {
charFrequency.put(c, charFrequency.getOrDefault(c, 0) + 1);
}
for (char c : str2.toCharArray()) {
if (!charFrequency.containsKey(c) || charFrequency.get(c) <= 0) {
return false;
}
charFrequency.put(c, charFrequency.get(c) - 1);
}
return true;
}
}
Output
Are 'listen' and 'silent' anagrams? true
Conclusion
In this article “Anagram program in Java”, we employed different approaches such as sorting, frequency counting, and utilizing HashMap to determine if two strings are anagrams.
Related Article