LeetCode-49、字母异位词分组-中等

mac2025-05-07  14

LeetCode-49、字母异位词分组-中等

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"], 输出: [   ["ate","eat","tea"],   ["nat","tan"],   ["bat"] ]

 

代码:

class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: dic = {} for word in strs: cur = str(sorted(word)) if cur not in dic: dic[cur] = [word] else: dic[cur].append(word) res = [] for key, value in dic.items(): res.append(value) return res # 或(1) # res = [] # for key in dic: # res.append(dic[key]) # return res # 或(2) # return list(dic.values())

最新回复(0)