LeetCode 热题 HOT 100 第二十二天 49. 字母异位词分组 中等题 用python3求解

题目地址

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。

示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]

示例 2:
输入: strs = [“”]
输出: [[“”]]

示例 3:
输入: strs = [“a”]
输出: [[“a”]]

提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母

在这里插入图片描述
主要是dict.get()函数的理解
dict.get(key, default=None)

  1. key – 字典中要查找的键。
  2. default – 如果指定键的值不存在时,返回该默认值。

还有一点要注意:因为字典的键,必须是不可变类型,所以用tuple。

代码实现:

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dict = {}
        for item in strs:
            key = tuple(sorted(item))
            #print('key:',key)
            dict[key] = dict.get(key, []) + [item]
            #print('dict:',dict)
        return list(dict.values())

以示例一为例,print过程输出:
key: (‘a’, ‘e’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’]}
key: (‘a’, ‘e’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’]}
key: (‘a’, ‘n’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’], (‘a’, ‘n’, ‘t’): [‘tan’]}
key: (‘a’, ‘e’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’, ‘ate’], (‘a’, ‘n’, ‘t’): [‘tan’]}
key: (‘a’, ‘n’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’, ‘ate’], (‘a’, ‘n’, ‘t’): [‘tan’, ‘nat’]}
key: (‘a’, ‘b’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’, ‘ate’], (‘a’, ‘n’, ‘t’): [‘tan’, ‘nat’], (‘a’, ‘b’, ‘t’): [‘bat’]}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值