力扣 49. 字母异位词分组

题目说明

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

字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母都恰好只用一次。

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

示例

示例 1:

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

示例 2:

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

示例 3:

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

笔者理解

此题是一道数组算法问题,在力扣题库中被定义为中等题。

解法

当笔者阅读完此题后,采用了字符排序并哈希表存储的方式,让我们来看看具体如何实现的吧。

实现

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
class Solution {
/*
* 字符串
* 哈希表
* 排序
*/
public List<List<String>> groupAnagrams(String[] strs) {
int n = strs.length;
List<List<String>> result = new ArrayList<>();
// 记录字符串和 对应存储的数组 在结果集中的下标
HashMap<String, Integer> map = new HashMap<>();
int tick = 0;

for (int i = 0; i < n; i++) {
List<String> list;
// 将字符串转化成字符数组排序并转化回字符串
char[] ch = strs[i].toCharArray();
Arrays.sort(ch);
String temp = new String(ch);

// 这样的字符串组合在 map 中不存在
if (map.getOrDefault(temp, -1) == -1) {
// 填入字符串组合,并将字符串标记加一
map.put(temp, tick++);
list = new ArrayList<>();
list.add(strs[i]);
result.add(list);
}
else {
result.get(map.get(temp)).add(strs[i]);
}

}

return result;
}
}

时间和空间效率一般,可见此解法还能用。

image-20210910103746543

总结

本题是今天的一题,难度是为中等,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。