题目:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
思路:把数组中的字符排序作为字典的键,字典的值存字符串。
代码:
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
aim = {}
for i in strs:
temp = "".join(sorted(i))
if temp not in aim.keys():
aim[temp] = [i]
else:
aim[temp].append(i)
# res = []
# for i in aim.keys():
# res.append(aim[i])
# return res
return list(aim.values())