给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
//遍历数组,对每个字符串进行操作
for (int i = 0; i < strs.length; i++) {
//把字符串转成字符数组
char[] ch = strs[i].toCharArray();
//排序
Arrays.sort(ch);
String s = new String(ch);
//取出对应的list,如果没有,新建
List<String> temp = map.getOrDefault(s, new ArrayList<>());
temp.add(strs[i]);
map.put(s, temp);
}
return new ArrayList<>(map.values());
}
}