49. 字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
解题思路:使用字典{key:value}来按照字母异位词分类存储字符串数组。key表示排序后的字符串,value表示key对应的字母异位词列表。
Python3代码如下:
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
result = {}
for string in strs:
s = ''.join(sorted(string))
if s in result:
result[s].append(string)
else:
result[s] = [string]
return [result[key] for key in result]