49.Group Anagrams(sorted,dict)

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.
class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        dict = {}
        for i in strs:
            key = ''.join(sorted(i))
            if key not in dict:
                dict[key] = [i]
            else:
                dict[key].append(i)
        return list(dict.values())

对于s='eat',那么sorted(s) = ['a','e','t'] 它返回的是一个list。而list是不可被哈希的元素。所以需要用key作为键,否则会报错。

可哈希的元素有:int、float、str、tuple
不可哈希的元素有:list、set、dict

posted @ 2018-10-08 13:00  bernieloveslife  阅读(105)  评论(0编辑  收藏  举报