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
原文地址:https://www.cnblogs.com/bernieloveslife/p/9750115.html
时间: 2024-11-08 23:38:02