Python 2-dictionary solution, beats 94.55% 55ms


  • 0
    R
            if s is None or t is None:
                return False
    
            if len(s) != len(t):
                return False
    
            s_dict = {}
            t_dict = {}
    
            for char in s:
                if char not in s_dict:
                    s_dict[char] = 1
                else:
                    s_dict[char] += 1
            
            for char in t:
                if char not in t_dict:
                    t_dict[char] = 1
                else:
                    t_dict[char] += 1
                    
            if s_dict == t_dict:
                return True
    
            return False
    

    We start off by making sure that we have strings in the first place, we then do a quick check to make sure the sizes are the same because if they are not, they cannot possibly form an anagram of each other.

    Then we go through each letter in the s string and add it to its own dictionary. Do the same for the t string, and then see if the dictionaries contain the same key value pairs.

    If they do, we know it can form an anagram and we return True.

    If not, then return False.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.