49_字母异位词分组
约 335 字大约 1 分钟
2026-03-08
给你一个字符串数组,请你将字母异位词组合在一起。可以按任意顺序返回结果列表。
示例:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
解释:
- 在 strs 中没有字符串可以通过重新排列来形成 "bat"。
- 字符串 "nat" 和 "tan" 是字母异位词,因为它们可以重新排列以形成彼此。
- 字符串 "ate" ,"eat" 和 "tea" 是字母异位词,因为它们可以重新排列以形成彼此。解题思路
- 构建一个哈希表
Map<String, List<String>>,Key 是排序后的字符串,Value 是互为字母异位词的原始字符串列表 - 遍历入参,对每一个字符串排序,排序后作为key,原始串放进 List 中作为 value,存入哈希表
- 用
map.values()将哈希表转换为 List
重点:
- 字符串转字符数组:
s.toCharArray() - 排序
Arrays.sort(chars)
3. Java 实现
排序法(最常见、最易写的标准解法)
import java.util.*;
class Solution {
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);
// 如果 key 不存在,则创建一个新的 ArrayList
map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(map.values());
}
}