变位词组
难度:
标签:
题目描述
Write a method to sort an array of strings so that all the anagrams are in the same group.
Note: This problem is slightly different from the original one the book.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Notes:
- All inputs will be in lowercase.
- The order of your output does not matter.
代码结果
运行时间: 39 ms, 内存: 18.6 MB
/*
* 思路:
* 1. 使用Java Streams对字符串数组进行流处理。
* 2. 对每个字符串进行排序,作为Map的键,将原始字符串作为值加入列表。
* 3. 最后收集Map中的所有值。
*/
import java.util.*;
import java.util.stream.Collectors;
public class AnagramGroupsStream {
public List<List<String>> groupAnagrams(String[] strs) {
// 使用Stream对字符串数组进行处理
return new ArrayList<>(Arrays.stream(strs)
// 对字符串进行排序
.collect(Collectors.groupingBy(str -> {
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
return new String(charArray);
}))
.values());
}
public static void main(String[] args) {
AnagramGroupsStream ags = new AnagramGroupsStream();
String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
System.out.println(ags.groupAnagrams(strs));
}
}
解释
方法:
此题解采用了哈希表来对字符串数组进行分类。对于数组中的每一个字符串,我们将其转换为字符列表并进行排序,使得所有的变位词都能得到相同的排序结果作为键(即哈希表的key)。然后,我们将原字符串加入到对应的哈希表条目中。最后,我们从哈希表中收集所有值,每个值都是一个变位词的组合,形成最终的结果列表。
时间复杂度:
O(n * m log m)
空间复杂度:
O(n * m)
代码细节讲解
🦆
为什么将每个字符串转换为字符列表并进行排序是识别变位词的有效方法?
▷🦆
在此题解中,哈希表的键是排序后的字符串,这种方法是否在所有情况下都能保证变位词分组的正确性?
▷🦆
如果输入字符串中包含Unicode字符或特殊符号,当前的排序和哈希键生成方法是否仍然适用?
▷