Python using dict without sort


  • 0
    S
    class Solution(object):
        def groupAnagrams(self, strs):
            """
            :type strs: List[str]
            :rtype: List[List[str]]
            """
            #key: tuple of the frequency of 26 letters, value: [string]
            d = collections.defaultdict(list)
            # only the frequency of each letter matters
            for s in strs:
                arr = [0] * 26
                for c in s:
                    arr[ord(c) - ord('a')] += 1
                d[tuple(arr)].append(s)
            # turn the values of dict into a list
            return list(d.values())

Log in to reply
 

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