首页 > 代码库 > 【LeetCode】49. Group Anagrams

【LeetCode】49. Group Anagrams

Given an array of strings, group anagrams together.

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

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

解法1:

把含有相同字母的字符串分之同一组,对每组的值sorted

1 class Solution(object):
2     def groupAnagrams(self, strs):
3         """
4         :type strs: List[str]
5         :rtype: List[List[str]]
6         """
7         return [sorted(x) for _,x in itertools.groupby(sorted(strs, key=sorted),key=sorted)]

解法2:

把每一个含有相同字母的字符串散列到同一个key,然后对每个value排序即得。

 1 class Solution(object):
 2     def groupAnagrams(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: List[List[str]]
 6         """
 7         dd = collections.defaultdict(list)
 8         for s in strs:
 9             dd[tuple(sorted(s))].append(s)
10         return map(sorted, dd.values())

 

【LeetCode】49. Group Anagrams