题目
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]输出:[["ate","eat","tea"],["nat","tan"],["bat"]]
思路
当且仅当它们的排序字符串相等时,两个字符串是字母异位词。
算法
维护一个映射 ans : {String -> List} ,其中每个键 K 是一个排序字符串,每个值是初始输入的字符串列表,排序后等于 K 。在 Python 中,我们将键存储为散列化元组,例如, ('c', 'o', 'd', 'e') 。
代码实现
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dic = {}
for item in strs:
key = tuple(sorted(item))
if key not in dic[key]:
dic[key] = [item] # 添加键和值 {('a', 'e', 't'): ['eat']}
else:
dic[key].append(item) # 添加值
return list(dic.values())
