标签:ase string mat tput 否则 ams eth return class
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
49.Group Anagrams(sorted,dict)
标签:ase string mat tput 否则 ams eth return class
原文地址:https://www.cnblogs.com/bernieloveslife/p/9750115.html