【leetcode】字母异位词分组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36372879/article/details/88555746

在这里插入图片描述


算法思路

这里采用字典的方法:将排序之后的单词作为key,匹配的单词作为value,每次遍历的时候,先要排序,然后判断是否在字典里面,最后输出所有的value就行了。

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        if List == []:
            return []
        dic = {}
        for item in strs:
            a = ''.join(sorted(item))
            if a in dic:
                dic[a].append(item)
            else:
                dic[a] = []
                dic[a].append(item)
        results = []
        for word in dic:
            results.append(dic[word])
        return results

猜你喜欢

转载自blog.csdn.net/weixin_36372879/article/details/88555746