[Leetcode] 49. Group Anagrams_Medium

本文介绍了一种使用Python实现的高效算法,该算法能够将一组字符串中的字谜进行分组。通过利用collections.defaultdict()创建字典并将相同模式的字符串归类在一起,最终返回所有分组结果。文章还附带了作者对于面试准备的一些建议。

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.

 

题目思路为利用collections.defualtdict() 去创建diction, 将相同模型的都append进去, 最后返回diction的所有values. 只是几个小细节要注意, 一个是diction不能以list作为key, 另外返回d.values()要加list.

 

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        #strs = set(strs)  # 问面试官, 如果有duplicates如何处理
        d = collections.defaultdict(list)
        for s in strs:
            template = [0]*26 #题目说只有lowcase
            for c in s:
                template[ord(c) - ord('a')] += 1
            d[tuple(template)].append(s)   # 注意加上tuple
        return list(d.values())  # 注意加上list

 

 

 

Thanks for your reply about the Interview details. I've received the email and will follow the instructions in it. At same time, is it possible to set a phone call with you or Dan Corslund that you mentioned in your last email to discuss more about the preparation of the interviews except the coding part?

         I am excited for the coming interviews and  see you all there.

 

Best regards,

Johnson

转载于:https://www.cnblogs.com/Johnsonxiong/p/9206907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值