题目:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
解答:
/**
思路:对strs中的每个字符串进行排序(不是对strs排序),如果两个字符串是字母异位词,那么它们排序后应该是相同的字符串,然后使用HashMap保存
**/
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(int i = 0; i < strs.length; i++){
//把字符串拆分为字符数组
char[] ch = strs[i].toCharArray();
//对字符数组进行排序,两个字母异位词排序后是相同的
Arrays.sort(ch);
//把排完序的字符数组重建为字符串String
String key = new String(ch);
//如果HashMap中已经包含,则在ArrayList中追加
if(map.containsKey(key)){
map.get(key).add(strs[i]);
}else{
//否则新建一个ArrayList,把当前字符串添加进去,再put进HashMap中
List<String> list = new ArrayList<>();
list.add(strs[i]);
map.put(key, list);
}
}
return new ArrayList<List<String>>(map.values());
}
}