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(). 

原文地址:https://www.cnblogs.com/prmlab/p/7141664.html