LeetCode 49. 字母异位词分组

49. 字母异位词分组

解题思路

将每个字符串排序后作为键,将所有排序后相同的字符串分组,最后返回分组结果

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for(String str : strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
if(!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(str);
}

// call map.values() to get the collection of all the values in the map!
// List<List<String>> result = new ArrayList<>();
// for(Map.Entry<String, List<String>> entry : map.entrySet()) {
// result.add(entry.getValue());
// }
return new ArrayList(map.values());
}
}

LeetCode 49. 字母异位词分组
https://sowink.cn/2026/02/06/LeetCode-49-字母异位词分组/
作者
Xurx
发布于
2026年2月6日
许可协议