Python 字符串哈希

题目大意

将字符组成相同的字符串分成一类

input

["eat", "tea", "tan", "ate", "nat", "bat"]

output

[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

Solution

由于python中tuple类型可以直接作为map的key,因此可以直接将需要哈希的字符串或者数组放入一个list,随后转成tuple,即可实现hashmap的功能。

此题只需将统计每个字母出现次数的桶哈希,最后在同一个哈希集合中的元素即为题意中的同一类字符。

from collections import defaultdict
from typing import List
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        mp = defaultdict(list)

        for str in strs:
            cnt = [0]*26
            for ch in str:
                cnt[ord(ch) - ord('a')] += 1
            mp[tuple(cnt)].append(str)

        return list(mp.values())

s = Solution()
print(s.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
原文地址:https://www.cnblogs.com/Yuzao/p/15026816.html