首页 > 其他 > 详细

[Leetcode] 49. Group Anagrams_Medium

时间:2018-06-21 10:11:38      阅读:183      评论:0      收藏:0      [点我收藏+]

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

[Leetcode] 49. Group Anagrams_Medium

原文:https://www.cnblogs.com/Johnsonxiong/p/9206907.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!