LeetCode 题解工作台

字母异位词分组

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 示例 1: 输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [["bat"],["nat","tan"],["ate","eat","tea"]] 解…

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

1. 遍历字符串,对每个字符串按照字符字典序排序,得到一个新的字符串。 2. 以新字符串为 `key`,`[str]` 为 `value`,存入哈希表当中(`HashMap<String, List<String>>`)。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

 

示例 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 <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] 仅包含小写字母
lightbulb

解题思路

方法一:哈希表

  1. 遍历字符串,对每个字符串按照字符字典序排序,得到一个新的字符串。
  2. 以新字符串为 key[str]value,存入哈希表当中(HashMap<String, List<String>>)。
  3. 后续遍历得到相同 key 时,将其加入到对应的 value 当中即可。

strs = ["eat", "tea", "tan", "ate", "nat", "bat"] 为例,遍历结束时,哈希表的状况:

key value
"aet" ["eat", "tea", "ate"]
"ant" ["tan", "nat"]
"abt" ["bat"]

最后返回哈希表的 value 列表即可。

时间复杂度 O(n×k×logk)O(n\times k\times \log k)。其中 nnkk 分别是字符串数组的长度和字符串的最大长度。

1
2
3
4
5
6
7
8
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())
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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

help

常见问题

外企场景

字母异位词分组题解:数组·哈希·扫描 | LeetCode #49 中等