问题描述
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
解题思路
哈希。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | from collections import defaultdict
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
def counting_sort(s: str) -> int:
count = [0] * 26
for c in s:
count[ord(c) - 97] += 1
for i in range(1, 26):
count[i] += count[i - 1]
r = [""] * len(s)
for c in s[::-1]:
i = ord(c) - 97
count[i] -= 1
r[count[i]] = c
return "".join(r)
s = defaultdict(list)
for x in strs:
s[counting_sort(x)].append(x)
return list(s.values())
|
| from collections import defaultdict
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
s = defaultdict(list)
for x in strs:
s["".join(sorted(x))].append(x)
return list(s.values())
|