49. Group Anagrams

0 阅读2分钟

问题

给定一个字符串数组 strs,将字母异位词组合在一起。返回的答案可以按任意顺序排列。

字母异位词(Anagram):由相同字母按照不同顺序排列组成的字符串,例如 "listen" 和 "silent"、"eat" 和 "tea" 均为字母异位词。

例1:

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

  • 解释:
    • There is no string in strs that can be rearranged to form "bat".
    • The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
    • The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.

例2:

输入: strs = [""] 输出: [[""]]

例3:

输入: strs = ["a"] 输出: [["a"]]

约束条件:

  • 字符串数组 strs 的长度满足:1 ≤ strs.length ≤ 10⁴(即数组中至少有 1 个字符串,最多不超过 10000 个字符串)
  • 数组中每个字符串 strs[i] 的长度满足:0 ≤ strs [i].length ≤ 100(即单个字符串可能为空字符串,最长不超过 100 个字符)
  • 字符串 strs[i] 仅由小写英文字母组成(无大写字母、数字、符号等其他字符)

解:哈希表

  1. 设原始数据在list1中,可以把每个单词按字母排序,显然所有的字母异位词排序后会得到相同的单词。
  2. 把该集合存入哈希表(key:排序后的单词。value:原始单词)。但是相同的key只能有1个,所以value是一个存储了原始单词的list
  3. 遍历所有key,分别把每个key对应的value存入list2。list2就是我们要的结果

image.png

时间复杂度O(nklogk)O(nklogk)nn是字符串数量,kk是字符串的最大长度。需要进行nn次排序操作,一次排序操作的时间复杂度是O(klogk)O(klogk)

空间复杂度O(nk)O(nk):随着数组规模的增大,我们使用哈希表的空间也会等比增大,需要额外占用的空间也会增大。

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        # 创建哈希表,key为排序后的字符串,value为原始字符串列表
        anagram_dict = {}
        for s in strs:
            # 对字符串按字母排序,作为哈希表的key
            sorted_str = ''.join(sorted(s))
            
            # 如果key已存在,将当前字符串添加到对应列表
            if sorted_str in anagram_dict:
                anagram_dict[sorted_str].append(s)
            # 如果key不存在,创建新的列表并添加当前字符串
            else:
                anagram_dict[sorted_str] = [s]
        # 将哈希表中的所有值(列表)组成新列表返回
        return list(anagram_dict.values())

参考

leetcode.cn/problems/gr…