LeetCode 49. 字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [“”]
输出: [[“”]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母
代码:
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
# 导入defaultdict,用于自动初始化字典的默认值
from collections import defaultdict
# 初始化一个defaultdict,其默认值为list,用于存储每个字母异位词组
d = defaultdict(list)
# 遍历输入的字符串列表strs
for s in strs:
# 对字符串s进行排序,得到一个排序后的字符串s_sorted
# 排序后的字符串作为字典的键,因为字母异位词排序后结果相同
s_sorted = ''.join(sorted(s))
# 将原始字符串s添加到字典d中,键为s_sorted,值为一个列表
# 同一字母异位词组的字符串会被添加到同一个列表中
d[s_sorted].append(s)
# 返回字典d的所有值,即分组后的字母异位词列表
return list(d.values())