Python 解leetcode:49. Group Anagrams

  • 题目描述:给出一个由字符串组成的数组,把数组中字符串的组成字母相同的部分放在一个数组中,并把组合后的数组输出;
  • 思路:
  1. 使用一个字典,键为数组中字符串排序后的部分,值为排序后相同的字符串组成的列表;
  2. 遍历数组完成后,返回字典的值就可以了。
class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        ret = {}
        for s in strs:
            ts = ‘‘.join(sorted(s))
            if ret.get(ts):
                ret[ts].append(s)
            else:
                ret[ts] = [s]
        return ret.values()
时间: 2024-10-09 12:38:49

Python 解leetcode:49. Group Anagrams的相关文章

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",

19.2.7 [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变位词归类

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","

[leetcode]49. Group Anagrams重排列字符串分组

是之前的重排列字符串的延伸,判断是重排列后存到HashMap中进行分组 这种HashMap进行分组的方式很常用 public List<List<String>> groupAnagrams(String[] strs) { /* 其实重排列的那个题是有两种做法的,之前整理的是比较好的的一种字母哈希表的方法,还有一种方法 是把字符串排序,然后进行比较就行. 这个题正好就是用了排序的方法,排序后的字符串作为key,list作为value就行 一开始想用字母哈希表的方法,结果没做出来

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

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

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

【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】Group Anagrams

题目链接:https://leetcode.com/problems/anagrams/ 题目: Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", &q