# Leetcode 49:字母异位词分组（最详细解决方案！！！）

xiaoxiao2021-02-28  7

Leetcode 242:有效的字母异位词（最详细解决方案！！！）

Leetcode 438:找到字符串中所有字母异位词（最详细解决方案！！！）

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

result例表中ate对应的位置应该是和eta和tea相同，都是0。于是我们就有了如下的算法

class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ strs_map = {} result = [] for i in strs: string = ''.join(sorted(i)) if string not in strs_map: strs_map[string] = len(result) result.append([string]) else: result[strs_map[string]].append(string) return result

class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ strs_map = {} result = [] for string in strs: tmp = ''.join(sorted(string)) if tmp in strs_map: strs_map[tmp].append(string) else: strs_map[tmp] = [string] for str_list in strs_map.values(): result.append(str_list) return result

class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ from collections import defaultdict dic = defaultdict(list) for s in strs: dic["".join(sorted(s))].append(s) return list(dic.values())