LeetCode--Python解析【Group Anagrams】(49)

题目:


方法:

首先将strs中的每一个字符串转换为list进行排序,再append进新的list中

此时字符串的顺序变为一致,但在strs中的索引没有变化

接下来构建一个dict,采用hash table的方法,遍历新的list

key值为字符串,value为出现的索引

最后把索引对应的字符串添加进新的列表中

输出,结束

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        temp = []
        dict1 = {}
        result = []
        for i in range(len(strs)):
            x = list(strs[i])
            x.sort()
            temp.append("".join(x))
        for i in range(len(temp)):
            if temp[i] not in dict1:dict1[temp[i]] = [i]
            else:dict1[temp[i]].append(i)
        print(dict1)
        for v in dict1:
            for j in range(len(dict1[v])):
                dict1[v][j] = strs[dict1[v][j]]
            result.append(dict1[v])
        return result

猜你喜欢

转载自blog.csdn.net/zjrn1027/article/details/80216782
今日推荐