字母异位词分组

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出: [
 ["ate","eat","tea"],
 ["nat","tan"],
 ["bat"]
]
说明:
 所有输入均为小写字母
 不考虑答案输出的顺序

思路:

用质数表示26个字母,把字符串的各个字母相乘,这样可保证字母异位词的乘积必定是相等的。

解答:

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        prime = (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)
        products = {}
        aVal = ord('a')
        for str in strs:
            prod = 1
            for c in str:
                prod *= prime[ord(c) - aVal]
            if prod not in products:
                products[prod] = [str]
            else:
                products[prod].append(str)
        
        return list(products.values())

你可能感兴趣的:(字母异位词分组)