给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
? https://leetcode-cn.com/classic/problems/group-anagrams/description/
异位词虽然字符的排序被打乱了,但是对其排序之后的结果都是一样的。例如: ate 和 tae 排序后都是 aet
排序 + 哈希
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = dict()
res = []
for i in strs:
strr = sorted(i) # 字符串排序之后返回一个list
st = ''
for j in strr:
st += j
if st not in ans:
ans[st] = []
ans[st].append(i)
else:
ans[st].append(i)
for i in ans:
res.append(ans[i])
return res