归档

49. 字母异位词分组

49. 字母异位词分组

题目

描述:

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

字母异位词 是由相同字母按不同顺序排列形成的字符串。

示例 1:

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

示例 2:

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

示例 3:

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

提示:

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] 仅包含小写字母

题解

为同一组字符串构造相同的键

如果逐对检查字符串是否为异位词,会反复统计相同内容。可以为每个字符串构造一个分组键:两个字符串的字母种类和次数完全相同时,键相同;组成不同时,键不同。这样每个字符串只需计算一次键,再通过哈希表找到所属组。

排序后的字符串就满足这个要求。"eat"、"tea"、"ate" 原始顺序不同,排序后都是 "aet"。排序结果同时反映了字符种类和每种字符的次数:"abb" 和 "aab" 字符种类都是 a、b,但排序后仍是 "abb" 和 "aab",不会被放进同一组。

遍历每个字符串,把排序结果作为键,原字符串加进该键对应的列表。以 strs = ["eat", "tea", "tan", "ate", "nat", "bat"] 为例,eat/tea/ate 的键都是 aet,tan/nat 的键都是 ant,bat 的键是 abt,哈希表里形成三个列表,每个列表就是一组异位词。

每个键对应一个 List<String>。第一次遇到键时创建空列表,随后把原字符串加入其中,不能把排序后的字符串当作输出。toCharArray() 创建了副本,所以排序不会改变原字符串。最后收集各个列表即可;题目不要求组与组的输出顺序,不能依赖 HashMap 的遍历顺序。

空字符串的键仍是空字符串,多个空串会分在一起;重复出现的相同字符串也分别保留。另一种键是按字母顺序编码 26 项频次,例如用 # 分隔每项计数。分隔符用于避免多位数字连接后产生歧义;下面采用更直观的排序键。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public List<List<String>> groupAnagrams(String[] strs) {
    if (strs == null || strs.length == 0) {
        return new ArrayList<>();
    }

    Map<String, List<String>> map = new HashMap<>();

    for (String s : strs) {
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        String key = new String(chars);

        if (!map.containsKey(key)) {
            map.put(key, new ArrayList<>());
        }

        map.get(key).add(s);
    }

    return new ArrayList<>(map.values());
}

设字符串数为 N、最大长度为 K。每个字符串都要生成排序后的键,期望时间上界为 O(N(1 + K log(K + 1)))。哈希表需保存分组引用和排序后的键,辅助空间上界为 O(N(1 + K))。

完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.*;

public class Main {

    public static List<List<String>> groupAnagrams(String[] strs) {
        if (strs == null || strs.length == 0) {
            return new ArrayList<>();
        }

        Map<String, List<String>> map = new HashMap<>();

        for (String s : strs) {
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);

            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<>());
            }

            map.get(key).add(s);
        }

        return new ArrayList<>(map.values());
    }

    // 按题面格式输出:字符串加引号,空字符串显示为 ""
    private static String quote(String[] arr) {
        StringJoiner sj = new StringJoiner(",", "[", "]");
        for (String x : arr) sj.add("\"" + x + "\"");
        return sj.toString();
    }

    private static String format(List<List<String>> groups) {
        StringJoiner sj = new StringJoiner(",", "[", "]");
        for (List<String> g : groups) sj.add(quote(g.toArray(new String[0])));
        return sj.toString();
    }

    public static void main(String[] args) {
        String[] strs1 = {"eat", "tea", "tan", "ate", "nat", "bat"};
        System.out.println("示例 1 输入: strs = " + quote(strs1));
        System.out.println("示例 1 输出: " + format(groupAnagrams(strs1)));
        System.out.println("-----------------------------");

        String[] strs2 = {""};
        System.out.println("示例 2 输入: strs = " + quote(strs2));
        System.out.println("示例 2 输出: " + format(groupAnagrams(strs2)));
        System.out.println("-----------------------------");

        String[] strs3 = {"a"};
        System.out.println("示例 3 输入: strs = " + quote(strs3));
        System.out.println("示例 3 输出: " + format(groupAnagrams(strs3)));
    }
}

运行结果(OpenJDK 21.0.12):

1
2
3
4
5
6
7
8
示例 1 输入: strs = ["eat","tea","tan","ate","nat","bat"]
示例 1 输出: [["eat","tea","ate"],["bat"],["tan","nat"]]
-----------------------------
示例 2 输入: strs = [""]
示例 2 输出: [[""]]
-----------------------------
示例 3 输入: strs = ["a"]
示例 3 输出: [["a"]]
本文由作者按照 CC BY 4.0 进行授权