题目链接:https://leetcode.cn/problems/group-anagrams/
难度:中等
描述:
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
提示:strs.length:[1, 10000]
题解
class Solution:def groupAnagrams(self, strs: List[str]) -> List[List[str]]:p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]m = dict(zip("abcdefghijklmnopqrstuvwxyz", p))# 实现自己的hash函数# python不会溢出,其他语言得考虑溢出问题temp = {}for s in strs:h = 1for c in s:h *= m[c]if h not in temp:temp[h] = [s]else:temp[h].append(s)return list(temp.values())
