Ritu Singh
Summary:
Suppose we have two strings A and B with N number of alphabets in it. Using Java, we have to find out whether both strings are anagrams of each other or not.
What is an anagram?
An anagram of a string is another string that contains the same characters, but the order of the characters can be different.
Note:-
If the strings are anagrams, you have to return True, or else return False
|s| represents the length of string s.
Solution:
Explanation:
Function Signature: The code defines a Java class named Solution with a static method isAnagram that takes two String parameters str1 and str2 and returns a boolean value indicating whether the two strings are anagrams of each other or not.
Input Validation: The method begins by checking if the lengths of str1 and str2 are equal. If they are not equal, it immediately returns false, indicating that the strings cannot be anagrams if their lengths differ.
Frequency Arrays: Two integer arrays freqStr1 and freqStr2 of size 26 are created to store the frequencies of characters in the input strings. These arrays represent the count of each alphabet (a-z) in the respective strings.
Character Frequency Calculation: The code iterates through each character of str1 and str2 using a loop. For each character, it calculates its index in the frequency array by subtracting the ASCII value of 'a' from the character's ASCII value. Then, it increments the corresponding index in the frequency array.
Comparison of Frequencies: After calculating the frequencies of characters in both strings, the code compares the frequency arrays freqStr1 and freqStr2. If any frequency value differs between the two arrays, the method returns false, indicating that the strings are not anagrams. If all frequencies match, the method returns true, indicating that the strings are indeed anagrams of each other.
Suggested blogs:
>How to route between different components in React.js?
>How to save Python yaml and load a nested class?-Python
>How to send multiple HTML form fields to PHP arrays via Ajax?
>What is data binding in Angular?
>What is microservice architecture, and why is it better than monolithic architecture?
>What makes Python 'flow' with HTML nicely as compared to PHP?
>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?
>Creating custom required rule - Laravel validation