Answer:
static boolean isAnagram(String a, String b) {
// 1 - Strings inequal in length can never be Anagram
if (a.length() != b.length()) {
return false;
}
// 2 - Convert both Strings to Lower Case
a = a.toLowerCase();
b = b.toLowerCase();
// 3 - Create an Array to store character count
int charCount[] = new int[26];
// 4 - Count Each Character
for (int i = 0; i < a.length(); i++) {
charCount[a.charAt(i) - 97]++;
charCount[b.charAt(i) - 97]--;
}
// 5 - Check for mismatching characters
for (int i = 0; i < charCount.length; i++) {
if (charCount[i] != 0) {
return false;
}
}
return true;
}
Step-by-step explanation:
Complete Questions:
Two strings, a and b, are called anagrams if they contain all the same characters in the same frequencies. For example, the anagrams of CAT are CAT, ACT, TAC, TCA, ATC, and CTA. Complete the function in the editor. If and are case-insensitive anagrams, print "Anagrams"; otherwise, print "Not Anagrams" instead.
Function:
static boolean isAnagram(String a, String b) {
// Complete the function
}
This algorithm has five steps to calculate whether two given strings are anagram or not.
- Check Strings length - If two strings don't have equal length, then they can never be anagrams. Because, anagrams contain same characters in the same frequencies.
- Convert both strings to lower case - in programming, 'A' is not equal to 'a'. So, we need to make sure we have letters in same case to avoid such errors.
- Create an Array for character count - We need some method to ensure that the strings are anagrams. So, here we will count the characters and decide if the strings are anagrams (as discussed in next point)
- Count each character - If String a has any character, we will increase the count of that character by 1. If String b has any character, we will decrease the count of that character by 1. At the end, if both strings have same characters in the same frequencies, all our character counts will be equal to 0.
- Check for mismatching characters - We check if all our character counts are equal to 0. If not, the function will return false, otherwise it will return true.