Python easy to understand solution with dictionary.


  • 2
    C
    """        
    def anagrams(self, strs):
        dic = {}
        for s in strs:
            dic[tuple(sorted(s))] = dic.get(tuple(sorted(s)),[]) + [s]
        res = []
        [res.extend(item) for item in dic.values() if len(item) > 1]
        return res
    """
    # Here is an updated version, where the order in each inner group is maintained:
    def groupAnagrams(self, strs):
        dic = {}
        for s in strs:
            dic[tuple(sorted(s))] = dic.get(tuple(sorted(s)),[]) + [s]
        return [sorted(item) for item in dic.values()]

  • 1
    C
    """ CAN NOT WORK ANYMORE
    Even shorter one:
    
    def anagrams(self, strs):
        dic = {}
        for s in strs:
            dic["".join(sorted(s))] = dic.get("".join(sorted(s)), 0) + 1
        return [s for s in strs if dic["".join(sorted(s))] > 1]
    """

  • 0
    S

    It's obvious your solution can't be accepted....


  • 0
    C

    Yes, for the updated question, this answer is not correct, but I have updated the answer above which is correct now.


  • 0
    S

    Yeah,this can pass.My previous solution is similar to yours,but it always failed due to time limit exceed.Thanks to yours,i understand why that happend.Thanks


Log in to reply
 

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