leetcode-python-字母异位词分组

1)先对所有字符串重排序,然后取set获得总共的分组个数。再逐个判断加入。时间复杂度太高了

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        def so(x):
            x= sorted(x)
            return ''.join(x)
        temp = list(map(so, strs))
        set_temp = list(set(temp))
        result = list()
        for i in range(len(set_temp)):
            result.append([])    
        for i in range(len(temp)):
            result[set_temp.index(temp[i])].append(strs[i])
        return result

2)哈希表+排序!字典的values也可以是列表!空间复杂度很低

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dic = dict()

        for i in strs:
            temp = ''.join(sorted(i))
            if temp not in dic.keys():
                dic[temp] = [i]
            else:
                dic[temp].append(i)
        return list(dic.values())

 

上一篇:day05 字典


下一篇:09字符编码