leetcode49 Group Anagrams

 1 """
 2 Given an array of strings, group anagrams together.
 3 Example:
 4 Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
 5 Output:
 6 [
 7   ["ate","eat","tea"],
 8   ["nat","tan"],
 9   ["bat"]
10 ]
11 """
12 class Solution:
13     def groupAnagrams(self, strs):
14         d = {}
15         for s in strs:
16             key = tuple(sorted(s))#!!!
17             d[key] = d.get(key, []) + [s] #!!!
18             #dict.get(key, default=None)
19             #key -- 字典中要查找的键。
20             #default -- 如果指定键的值不存在时,返回该默认值
21         return d.values()

 

posted @ 2020-02-25 22:26  yawenw  阅读(112)  评论(0编辑  收藏  举报