49.Group Anagrams(sorted,dict)

Given an array of strings, group anagrams together.

Example:

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

Output:

[

["ate","eat","tea"],

["nat","tan"],

["bat"]]

Note:

All inputs will be in lowercase.
The order of your output does not matter.
class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        dict = {}
        for i in strs:
            key = ‘‘.join(sorted(i))
            if key not in dict:
                dict[key] = [i]
            else:
                dict[key].append(i)
        return list(dict.values())

对于s=‘eat‘,那么sorted(s) = [‘a‘,‘e‘,‘t‘] 它返回的是一个list。而list是不可被哈希的元素。所以需要用key作为键,否则会报错。

可哈希的元素有:int、float、str、tuple

不可哈希的元素有:list、set、dict

原文地址:https://www.cnblogs.com/bernieloveslife/p/9750115.html

时间: 2024-11-08 23:38:02

49.Group Anagrams(sorted,dict)的相关文章

49. Group Anagrams(js)

49. Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], [&q

LeetCode开心刷题二十六天——49.Group Anagrams

49. Group Anagrams Medium 1824116FavoriteShare Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat

【LeetCode】49. Group Anagrams

Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat",

49. Group Anagrams (string, map)

Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat",

Leetcode 49. Group Anagrams

Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat",

【一天一道LeetCode】#49. Group Anagrams

一天一道LeetCode系列 (一)题目 Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"

49. Group Anagrams同义词合并

[抄题]: Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat"

[leetcode]49. Group Anagrams变位词归类

Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","

LeetCode 49. Group Anagrams HashTable

Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","