小白的第二篇LeetCode(国际版)英文题解 - Problem. 49

Python ||🔥 Extremely SHORT (5 lines!) & EASY 🔥|| Fully exploit Python

Group Anagrams - LeetCodeLevel up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.icon-default.png?t=N7T8https://leetcode.com/problems/group-anagrams/solutions/4684931/python-extremely-short-5-lines-easy-fully-exploit-pythonIntuition 

Intuitively, we can think of each group as an equivalent class.
Moreover, let the sorted equivalent of any word in a class symbolize the class, which forms a string\to group mapping so that we can implement directly using dict in Python.

Approach

  • Sort a string s using ''.join(sorted(s)), where sorted(s) returns a list.
  • In order to reduce the underlying time constant for comparing in the Python dictionary, we can use the hashes of strings as the keys (see Code).
  • As to generating the final output from our mp: dictlist(mp.values()) is enough!

Code

class Solution:
    def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
        mp = {}
        for s in strs:
            h = hash(''.join(sorted(s)))
            mp[h] = mp.get(h, []) + [s]
        return list(mp.values())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值