Type-1:
An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once.
To check if two given strings are anagrams of each other, we need to ensure that they have the same characters with the same frequency, even if the characters are in a different order.
Let's create a Java function to accomplish this:
public class AnagramChecker {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println("The strings are anagrams.");
}
else {
System.out.println("The strings are not anagrams.");
}
}
public static boolean areAnagrams(String str1, String str2) {
// Remove all non-alphabetic characters and convert the strings to lowercase
str1 = str1.replaceAll("[^a-zA-Z]", "").toLowerCase();
str2 = str2.replaceAll("[^a-zA-Z]", "").toLowerCase();
// Check if the strings have the same length after removing non-alphabetic characters
if (str1.length() != str2.length()) {
return false;
}
// Create an array to store the frequency of each character
int[] charFrequency = new int[26];
// Count the frequency of characters in the first string
for (char ch : str1.toCharArray()) {
charFrequency[ch - 'a']++;
}
// Decrement the frequency of characters in the second string
for (char ch : str2.toCharArray()) {
charFrequency[ch - 'a']--;
}
// Check if all character frequencies are zero
for (int frequency : charFrequency) {
if (frequency != 0) {
return false;
}
}
return true;
}
}
Explanation:
1. We start with the main method, where we declare and initialize two string variables, str1 and str2, representing the two strings we want to check if they are anagrams. In this example, str1 is set to "listen," and str2 is set to "silent."
2. Next, we call the areAnagrams method, passing str1 and str2 as arguments, to determine if the two strings are anagrams.
3. In the areAnagrams method, we first remove all non-alphabetic characters from both input strings using the replaceAll() method with a regular expression "[^a-zA-Z]" (matches any character that is not an uppercase or lowercase letter). We also convert the strings to lowercase using toLowerCase() to handle cases where the input strings have mixed uppercase and lowercase characters.
4. We then check if the lengths of the modified str1 and str2 are the same. If they have different lengths, they cannot be anagrams, so we return false.
5. Next, we create an integer array charFrequency of size 26 (representing the 26 lowercase English letters) to store the frequency of each character in the strings.
6. We iterate through the characters of str1 using a for-each loop. For each character, we increment the corresponding position in charFrequency. For example, if the character is 'a', we increment charFrequency[0], and if it's 'b', we increment charFrequency[1], and so on.
7. Similarly, we iterate through the characters of str2, but this time we decrement the corresponding position in charFrequency.
8. After both iterations, the charFrequency array will contain the differences in character frequency between str1 and str2.
9. We then check if all elements of charFrequency are zero. If any element is non-zero, it means that the frequencies of characters in str1 and str2 are not the same, and thus, the strings are not anagrams. In this case, we return false.
10. If all character frequencies are zero, it means that the strings have the same characters with the same frequency, and we return true, indicating that the strings are anagrams.
By implementing this function, we can efficiently determine if two given strings are anagrams of each other, regardless of the case and non-alphabetic characters present in the strings.
Tyep-2:
Another way to check if two given strings are anagrams of each other is by sorting the characters in both strings and then comparing the sorted strings.
If the sorted strings are the same, the original strings are anagrams. This approach ensures that both strings contain the same characters with the same frequency, regardless of their original order.
Let's create a Java function using this approach:
import java.util.Arrays;
public class AnagramChecker {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}
public static boolean areAnagrams(String str1, String str2) {
// Remove all non-alphabetic characters and convert the strings to lowercase
str1 = str1.replaceAll("[^a-zA-Z]", "").toLowerCase();
str2 = str2.replaceAll("[^a-zA-Z]", "").toLowerCase();
// Sort the characters in both strings
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// Compare the sorted strings
return Arrays.equals(charArray1, charArray2);
}
}
Explanation:
1. The code structure and the declaration of the main method are the same as before, where we have str1 and str2 as the two strings we want to check if they are anagrams.
2. We call the are anagrams method, passing str1 and str2 as arguments, to determine if the two strings are anagrams.
3. In the anagrams method, we first remove all non-alphabetic characters from both input strings and convert them to lowercase, just like in the previous implementation.
4. Next, we convert both strings into character arrays, charArray1 and charArray2, respectively.
5. We then use the Arrays.sort() method to sort the characters in both charArray1 and charArray2 in ascending order.
6. Finally, we compare the sorted arrays using the Arrays.equals() method. If the sorted arrays are equal, it means that the original strings are anagrams, and we return true. Otherwise, we return false.
The sorting-based approach provides an alternative and straightforward way to check if two given strings are anagrams of each other. It sorts the characters in both strings, allowing us to compare them easily and efficiently.
Type-3:
Another way to check if two given strings are anagrams of each other is by using character frequency maps. We can create frequency maps for both strings, where each key-value pair represents a character and its frequency in the string. If the frequency maps of both strings are identical, the original strings are anagrams.
Let's create a Java function using this approach:
import java.util.HashMap;
import java.util.Map;
public class AnagramChecker {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}
public static boolean areAnagrams(String str1, String str2) {
// Remove all non-alphabetic characters and convert the strings to lowercase
str1 = str1.replaceAll("[^a-zA-Z]", "").toLowerCase();
str2 = str2.replaceAll("[^a-zA-Z]", "").toLowerCase();
// Check if the lengths of the modified strings are the same
if (str1.length() != str2.length()) {
return false;
}
// Create frequency maps for both strings
Map<Character, Integer> frequencyMap1 = createFrequencyMap(str1);
Map<Character, Integer> frequencyMap2 = createFrequencyMap(str2);
// Compare the frequency maps
return frequencyMap1.equals(frequencyMap2);
}
public static Map<Character, Integer> createFrequencyMap(String str) {
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char ch : str.toCharArray()) {
frequencyMap.put(ch, frequencyMap.getOrDefault(ch, 0) + 1);
}
return frequencyMap;
}
}
Explanation:
1. The code structure and the declaration of the main method are similar to the previous implementations.
2. We call the are anagrams method, passing str1 and str2 as arguments, to determine if the two strings are anagrams.
3. In the anagrams method, we first remove all non-alphabetic characters from both input strings and convert them to lowercase, just like before.
4. We then check if the lengths of the modified str1 and str2 are the same. If they have different lengths, they cannot be anagrams, so we return false.
5. Next, we create frequency maps for both strings using the createFrequencyMap method. The frequencyMap is a Map that stores each character in the string as a key and its frequency as the value.
6. The createFrequencyMap method iterates through each character in the input string. For each character, it checks if it exists in the frequencyMap. If the character is already present, it increments its frequency count. If not, it adds the character to the map with a frequency of 1.
7. Once the frequency maps are created for both str1 and str2, we use the equals() method to compare the two frequency maps. If they are equal, it means that the original strings are anagrams, and we return true. Otherwise, we return false.
Using frequency maps provides a different approach to check if two given strings are anagrams. It relies on character frequency counts rather than sorting, making it an efficient and straightforward method for anagram detection.
0 Comments