Concise Python solution beats 72.9%

  • 0
    from collections import defaultdict
    class Solution(object):
        def groupAnagrams(self, strs):
            :type strs: List[str]
            :rtype: List[List[str]]
            if not strs or len(strs) == 0:
                return []
            strDict = defaultdict(list) # use defualtdict(list) to get things faster(dict() still works anyway)
            for s in strs:
                ch = ''.join(sorted(s)) #sort string s
                strDict[ch].append(s) #append s to strDict[ch](strDict[ch] will generate an empty list if ch not in strDict)
            return strDict.values()

Log in to reply

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