2 solution in Python O(n*lg n) and O(n)


  • 0
    A

    one is sort

    class Solution:
    # @param {string} s
    # @param {string} t
    # @return {boolean}
    def isAnagram(self, s, t):
        return sorted(s) == sorted(t)
    

    the other one is map

    class Solution:
    # @param {string} s
    # @param {string} t
    # @return {boolean}
    def isAnagram(self, s, t):
        dic = {}
        for c in s:
            if c not in dic:
                dic[c] = 0
            dic[c] += 1
        
        for c in t:
            if c not in dic:
                return False
            dic[c] -= 1
            if dic[c] < 0:
                return False
        
        for k in dic.keys():
            if dic[k] != 0:
                return False
        
        return True

Log in to reply
 

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