Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
把字符串排好序的结果作为key,同一个key的字符串组成的队列作为value,构建一个字典。然后将字典的value排序,append到结果返回。这和java中的hashmap很相似。class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
d, ans = {}, []
for i in strs:
sortstr = ''.join(sorted(i))
if sortstr in d:
d[sortstr] += [i]
else:
d[sortstr] = [i]
for i in d:
tmp = d[i]
tmp.sort()
ans += [tmp]
return ans