LeetCode49. Group Anagrams
Posted wilderness
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode49. 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())
以上是关于LeetCode49. Group Anagrams的主要内容,如果未能解决你的问题,请参考以下文章