[leetcode] 49. Group Anagrams @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86628605

原题

Given an array of strings, group anagrams together.

Example:

Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
Note:

All inputs will be in lowercase.
The order of your output does not matter.

解法

构造defaultdict, 用列表作为它的value, 将单词排序后转化为元组作为它的key
Time: O(n)
Space: O(1)

代码

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        d = collections.defaultdict(list)
        for s in strs:
            tup = tuple(sorted(s))
            d[tup].append(s)
        return [d[k] for k in d]

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86628605
今日推荐