Skip to main content

49. 字母异位词分组 [medium]

49. 字母异位词分组 [medium]

https://leetcode-cn.com/problems/group-anagrams/

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

示例:

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

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。

通过次数91,292 | 提交次数145,281

First Try

2020-07-28

这种直接对字符串进行排序的写法,占用空间较多,但思路清晰速度快啊。

class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
mapping = [''.join(sorted(s)) for s in strs]
col = collections.defaultdict(list)
for i in range(len(strs)):
col[mapping[i]].append(strs[i])
return list(col.values())
  • 执行用时:52 ms, 在所有 Python3 提交中击败了95.23%的用户
  • 内存消耗:16.7 MB, 在所有 Python3 提交中击败了14.29%的用户