Commented python solution using defaultdict, 264ms


  • 1
    M

    from collections import defaultdict

    class Solution(object):
    def groupAnagrams(self, strs):
    """
    :type strs: List[str]
    :rtype: List[List[str]]
    """

        # split words into characters
        # sort words by lexicographic order
        character_sets = [sorted(list(str)) for str in strs]
        
        # create tuple and append word index to dictionary of list
        d = defaultdict(list)
        for index, character_set in enumerate(character_sets):
            d[tuple(character_set)].append(index)
        
        # iterate values of dictionary and append to result list
        res = []
        for group in d.itervalues():
            res.append(sorted([strs[index] for index in group]))
        return res

Log in to reply
 

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