【python/M/49】Group Anagrams

题目

这里写图片描述

基本思路

这个题目比较简单,主要分为两步:
1. 构建一个字典,字典中key是排序过的单词(比如’aet’),value是单词列表(比如[‘eat’,’ate’])
2. 对字典遍历,将value都append到结果列表中

代码

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        adict = {}      
        for item in strs:
            akey = ''.join(sorted(item))  
            if akey in adict.keys():
                adict[akey] += [item]
            else:
                adict[akey] = [item]

        res = []
        for v in adict.values():
            res.append(v)

        return res

运行结果

101 / 101 test cases passed.
Status: Accepted
Runtime: 120 ms

猜你喜欢

转载自blog.csdn.net/alicelmx/article/details/81128036