2. Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Code
Overall, the approach uses a HashMap
to count the occurrences of each character in the first string and then decrements those counts based on the characters in the second string. If all counts are zero at the end, the two strings are anagrams.
The method converts both strings into character arrays (
firstStringArray
andsecondStringArray
) for easier manipulation.If the lengths of the two arrays are not equal, the method immediately returns
false
, since anagrams must have the same number of characters.A
HashMap
namedstringHolderHashmap
is initialized to keep track of character counts. The method iterates throughfirstStringArray
and counts occurrences of each character:If the character already exists in the map, its count is incremented.
If it doesn’t exist, it is added to the map with a count of
1
.
The method then iterates through
secondStringArray
and decreases the counts of each character in thestringHolderHashmap
:If the character from
secondStringArray
exists in the map, its count is decremented by1
.
Finally, the method checks if all counts in the
stringHolderHashmap
are0
. If any count is not0
, it means that the characters in the two strings do not match up completely, and the method returnsfalse
.If all counts are
0
, the method concludes thats
andt
are anagrams and returnstrue
.
This might not be the optimal solution, but it’s a starting point for my work. As I progress, I hope to enhance my coding style along the way.
Last updated