小白的第二篇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())

你可能感兴趣的:(Leetcode,刷题,leetcode,算法,python)