题目描述给定一个字符串数组strs将字母异位词组合在一起。字母异位词指字母相同但排列不同的字符串。示例输入[eat, tea, tan, ate, nat, bat]示例输出[[bat], [nat, tan], [ate, eat, tea]]解题思路字母异位词的核心特征是字符组成相同但顺序不同。因此可以通过对字符串排序或统计字符频率的方式将异位词映射到同一键值。方法一排序 哈希表将每个字符串排序后的结果作为哈希表的键原字符串作为值的一部分。异位词排序后结果相同自然会被分到同一组。时间复杂度O(NKlogK)其中 N 是字符串数量K 是字符串最大长度。空间复杂度O(NK)。方法二字符计数 哈希表统计每个字符串中字符的出现频率将频率数组转换为字符串作为哈希表的键。例如aab的频率表示为a2b1。时间复杂度O(NK)。空间复杂度O(NK)。Java 代码实现方法一实现import java.util.*; class Solution { public ListListString groupAnagrams(String[] strs) { MapString, ListString 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()); } }方法二实现import java.util.*; class Solution { public ListListString groupAnagrams(String[] strs) { MapString, ListString map new HashMap(); for (String s : strs) { int[] count new int[26]; for (char c : s.toCharArray()) { count[c - a]; } StringBuilder sb new StringBuilder(); for (int i 0; i 26; i) { if (count[i] 0) { sb.append((char) (a i)).append(count[i]); } } String key sb.toString(); map.computeIfAbsent(key, k - new ArrayList()).add(s); } return new ArrayList(map.values()); } }关键点分析哈希表的选择两种方法均依赖哈希表实现分组但键的生成方式不同。方法一适合短字符串方法二适合字符分布稀疏的长字符串。优化技巧在方法二中使用StringBuilder拼接频率字符串比直接拼接更高效。边界处理输入为空数组时两种方法均返回空列表。复杂度对比| 方法 | 时间复杂度 | 空间复杂度 | |--------------------|------------------|------------------| | 排序 哈希表 | O(NKlogK) | O(NK) | | 字符计数 哈希表 | O(NK) | O(NK) |实际应用场景此类问题常见于文本处理或数据分析领域例如日志文件中统计相同错误类型的消息。生物信息学中识别基因序列的相似片段。https://github.com/cbar1239/etj_f3a4/blob/main/README.mdhttps://raw.githubusercontent.com/cbar1239/etj_f3a4/main/README.mdhttps://github.com/pjongfreemen/xka_2ayghttps://github.com/pjongfreemen/xka_2ayg/blob/main/README.mdhttps://raw.githubusercontent.com/pjongfreemen/xka_2ayg/main/README.md