LeetCode 题解工作台
字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 示例 1: 输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [["bat"],["nat","tan"],["ate","eat","tea"]] 解…
4
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
1. 遍历字符串,对每个字符串按照字符字典序排序,得到一个新的字符串。 2. 以新字符串为 `key`,`[str]` 为 `value`,存入哈希表当中(`HashMap<String, List<String>>`)。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
解释:
- 在 strs 中没有字符串可以通过重新排列来形成
"bat"。 - 字符串
"nat"和"tan"是字母异位词,因为它们可以重新排列以形成彼此。 - 字符串
"ate","eat"和"tea"是字母异位词,因为它们可以重新排列以形成彼此。
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
1 <= strs.length <= 1040 <= strs[i].length <= 100strs[i]仅包含小写字母
解题思路
方法一:哈希表
- 遍历字符串,对每个字符串按照字符字典序排序,得到一个新的字符串。
- 以新字符串为
key,[str]为value,存入哈希表当中(HashMap<String, List<String>>)。 - 后续遍历得到相同
key时,将其加入到对应的value当中即可。
以 strs = ["eat", "tea", "tan", "ate", "nat", "bat"] 为例,遍历结束时,哈希表的状况:
| key | value |
|---|---|
"aet" |
["eat", "tea", "ate"] |
"ant" |
["tan", "nat"] |
"abt" |
["bat"] |
最后返回哈希表的 value 列表即可。
时间复杂度 。其中 和 分别是字符串数组的长度和字符串的最大长度。
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = defaultdict(list)
for s in strs:
k = ''.join(sorted(s))
d[k].append(s)
return list(d.values())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand how hash tables can be used to group strings efficiently?
- question_mark
Can you explain the trade-off between sorting strings and using frequency counts?
- question_mark
Will you consider edge cases such as empty strings and strings with single characters?
常见陷阱
外企场景- error
Forgetting to handle empty strings, which should be grouped correctly.
- error
Not efficiently handling large inputs, especially when the number of strings is high (up to 10^4).
- error
Assuming the problem only requires sorting the input, rather than considering the hashing approach.
进阶变体
外企场景- arrow_right_alt
Group Anagrams with case sensitivity
- arrow_right_alt
Group Anagrams with longer strings up to length 100
- arrow_right_alt
Group Anagrams with additional constraints like handling non-English characters