Python 3 solutions: sort, O(n) time/space


  • 0
    class SolutionList(object):
        def isAnagram(self, s, t):
            l = [0]*27
            to_int = lambda l: ord(l)-ord('a') if l else 26
            for l1, l2 in map(None, s, t):
                l[to_int(l1)] += 1
                l[to_int(l2)] -= 1
    
            return not any(l[:26])
    
    from collections import defaultdict
    class SolutionDefaultDict(object):
        def isAnagram(self, s, t):
            d = defaultdict(int)
            for l1, l2 in map(None, s, t):
                d[l1] += 1
                d[l2] -= 1
    
            return not any(d.values())
    
    class SolutionSorted(object):
        def isAnagram(self, s, t):
            return sorted(s) == sorted(t)
    

Log in to reply
 

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