Skip to content

Files

Latest commit

 

History

History
31 lines (27 loc) · 886 Bytes

49.md

File metadata and controls

31 lines (27 loc) · 886 Bytes

题目地址

https://leetcode-cn.com/problems/group-anagrams/

解答

def groupAnagrams(strs):
    """
        字母异位词分组

        输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
        输出:
        [
          ["ate","eat","tea"],
          ["nat","tan"],
          ["bat"]
        ]
    """
    chardict = {'a': 2, 'b': 3, 'c': 5, 'd': 7, 'e': 11, 'f': 13, 'g': 17, 'h': 19, 'i': 23, 'j': 29, 'k': 31, 'l': 37,
                'm': 41, 'n': 43, 'o': 47, 'p': 53, 'q': 59, 'r': 61, 's': 67, 't': 71, 'u': 73, 'v': 79, 'w': 83,
                'x': 89, 'y': 97, 'z': 101}
    ans = collections.defaultdict(list)

    for string in strs:
        temp = 1
        for char in string:
            temp *= chardict[char]
        # 用字符串内字符对应的质数值的乘积作为键值
        ans[temp].append(string)

    return list(ans.values())