Share my accepted python code


  • 1
    S
    class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        mydict = dict()
        results = []
        for item in strs:
            item_ele = tuple(sorted(item))
            if not item_ele in mydict:
                mydict[item_ele] = [item]
            else:
                mydict[item_ele].append(item)
        for key in mydict:
            item_array = mydict[key]
            item_array.sort()
            results.append(item_array)
        return results

  • 2
    S

    Updated concise version.

    class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        mydict = dict()
        for item in strs:
            item_ele = tuple(sorted(item))
            mydict[item_ele] = mydict.get(item_ele,[]) + [item]
        return [sorted(item) for item in mydict.values()]

Log in to reply
 

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