1、题目描述
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"], 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
2、题解
2.1、解法一
原理:使用每个字符串排序,然后作为字典的key,源字符串作为value。
class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ dic = {} for i in strs: k = tuple(sorted(i)) if k not in dic: dic[k] = [] dic[k].append(i) return [dic[k] for k in dic]