Python code using a dictionary

  • 0
    class Solution(object):
        def groupAnagrams(self, strs):
            :type strs: List[str]
            :rtype: List[List[str]]
            n = len(strs)
            if n == 0:
                return []
            D = {}  # in the dict, key is the prototype string of the list of strings (value)
            for i in xrange(n):
                cur_type = ''.join(sorted(strs[i])) # change to prototype
                if cur_type in D:
                    D[cur_type].append(strs[i]) # add to the list
                else:  # not found in 'D'
                    D[cur_type] = [strs[i]] # create a new pair
            return [v for (k, v) in D.items()]

Log in to reply

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