思路:将单词拆分出来的字符作为dict的key即可。
注意:python中key不能是list,需要转成tuple类型。
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
if not strs:
return []
mydict = {}
for word in strs:
chList = list(word)
chList.sort()
if tuple(chList) in mydict.keys():
mydict[tuple(chList)].append(word)
else:
mydict[tuple(chList)] = [word]
ans = []
for value in mydict.values():
ans.append(value)
return ans