2. Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Code
class Solution {
    public boolean isAnagram(String s, String t) {
        char[] firstStringArray = s.toCharArray();
        char[] secondStringArray = t.toCharArray();
        if (firstStringArray.length != secondStringArray.length) {
            return false;
        }
        HashMap<String, Integer> stringHolderHashmap = new HashMap<String, Integer>();
        for (int index = 0; index < firstStringArray.length; index++) {
            if (stringHolderHashmap.containsKey(String.valueOf(firstStringArray[index]))) {
                int value = stringHolderHashmap.get(String.valueOf(firstStringArray[index]));
                value += 1;
                stringHolderHashmap.put(String.valueOf(firstStringArray[index]), value);
            } else {
                stringHolderHashmap.put(String.valueOf(firstStringArray[index]), 1);
            }
        }
        for (int index = 0; index < secondStringArray.length; index++) {
            if (stringHolderHashmap.containsKey(String.valueOf(secondStringArray[index]))) {
                int value = stringHolderHashmap.get(String.valueOf(secondStringArray[index]));
                value -= 1;
                stringHolderHashmap.put(String.valueOf(secondStringArray[index]), value);
            }
        }
        for(String key : stringHolderHashmap.keySet()) {
            int value = stringHolderHashmap.get(key);
            if (value != 0) {
                return false;
            }
        }
        return true;
    }
}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 (
firstStringArrayandsecondStringArray) 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
HashMapnamedstringHolderHashmapis initialized to keep track of character counts. The method iterates throughfirstStringArrayand 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
secondStringArrayand decreases the counts of each character in thestringHolderHashmap:If the character from
secondStringArrayexists in the map, its count is decremented by1.
Finally, the method checks if all counts in the
stringHolderHashmapare0. 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 thatsandtare anagrams and returnstrue.
Last updated