zoukankan      html  css  js  c++  java
  • 49. Group Anagrams

    https://leetcode.com/problems/group-anagrams/#/description

    Given an array of strings, group anagrams together.

    For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
    Return:

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

    Note: All inputs will be in lower-case.

    Sol:

    class Solution(object):
        def groupAnagrams(self, strs):
            """
            :type strs: List[str]
            :rtype: List[List[str]]
            """
            if len(strs) < 2:
                return [strs]
            
            dic = {}
            for string in strs:
                key = tuple(sorted(string))
                dic[key] = dic.get(key, []) + [string]
            return dic.values()
                
                

    Note:

    1 dictionary.get(key, default = None) or you can change the default variable to return anything you like when key not found.

    ex. dic.get(key, [])

    if key not found, return empty brackets so that it can be added by non-empty brackets. 

    2 dict.values()  

    return all values in the dict as a list 

    >>> dict = { 1 : 2, 'a' : 'b', 'hello' : 'world' }  
    >>> dict.values()  
    ['b', 2, 'world']  
    >>> dict.keys()  
    ['a', 1, 'hello']  
    >>> dict.items()  
    [('a', 'b'), (1, 2), ('hello', 'world')]  

    3 string is not hashable....but we can transform string into tuple using tuple(). 

  • 相关阅读:
    jQuery-选择器及属性修改
    jQuery 基础理论
    CSS 之 BFC(块级格式化上下文)
    H5--Web Storage
    H5 -WebWorker
    H5 --拖放
    nodejs Multer中间件
    k8s pod
    kubernetes
    优化CUDA数据传输
  • 原文地址:https://www.cnblogs.com/prmlab/p/7141664.html
Copyright © 2011-2022 走看看