2021-07-18 LeetCode 面试题 10.02. 变位词组

面试题 10.02. 变位词组

代码

很容易想到的哈希表,每个字符串对应字母的个数都一样,一样的是一组。所以用字母个数作为map的key值。此处由于是刚开始从java转到python刷题,所以附上相关语法学习记录。

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        mp=collections.defaultdict(list)

        for s in strs:
        	# [0,0,0,0,0,0,0,0,...]
            counts=[0]*26
            for ch in s:
            # 必须要用ord才能获得对应的ASCII数值
                counts[ord(ch)-ord('a')]+=1
            # list不能hash,tuple才可以
            mp[tuple(counts)].append(s)
        
        return list(mp.values())

collections.defaultdict(list)

collections.defaultdict()的用法示例
1.输出 dict_items([(‘yellow’, [1, 3]), (‘blue’, [2, 4]), (‘red’, [1])])

import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

# defaultdict
d = collections.defaultdict(list)
for k, v in s:
    d[k].append(v)
print(d.items())
#原文链接:https://blog.csdn.net/weixin_44110891/article/details/89575020

2.输出 dict_items([(‘yellow’, {1, 3}), (‘blue’, {2, 4}), (‘red’, {1})])

import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(set)
for k, v in s:
    d[k].add(v)
print(d.items())
#原文链接:https://blog.csdn.net/weixin_44110891/article/details/89575020

3.输出 dict_items([(‘m’, 1), (‘i’, 4), (‘s’, 4), (‘p’, 2)])

import collections
s = 'mississippi'
d = collections.defaultdict(int)
for k in s:
    d[k] += 1
print(d.items())
#原文链接:https://blog.csdn.net/weixin_44110891/article/details/89575020
上一篇:Python-Collections模块之defaultdict


下一篇:Python代码阅读(第7篇):列表分组计数