给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i]
仅包含小写字母
方法一:排序【时间复杂度:O(nmlogm), n 为 strs 的长度,m 为 strs[i] 的长度】
class Solution { //方法一:排序,使用HashMap
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> hashmap = new HashMap<>();
for(String str : strs){ //遍历字符串数组
char[] s = str.toCharArray(); //字符串转成字符数组
Arrays.sort(s); //对字母进行排序
if(hashmap.containsKey(new String(s))){
// 先判断hashmap中是否有排序后的字母作为key,有的话直接获取list值,添加未排序的str
hashmap.get(new String(s)).add(str);
}else{
// hashmap中没有排序后的字母作为的key,创建一个新的list,添加str
List<String> temp = new ArrayList<>();
temp.add(str);
hashmap.put(new String(s), temp);
}
}
return new ArrayList<>(hashmap.values());
}
}