码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] 49. Group Anagrams_Medium

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

标签:NPU   anagrams   you   androi   cti   color   cal   att   cep   

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

标签:NPU   anagrams   you   androi   cti   color   cal   att   cep   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!