给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入:
["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
思路:这题不会做,是看大神怎么做的,总结下思路,这里姑且叫这种思路为 「字典排序」吧,利用 Map 的键值对,来加入对应的值,因为字母异位,但是总体还是那几个字母,将其按照从小到大的顺序作为键值,那么依靠这种键值加入字母异位的字符串,最后返回 map 的values 即可。
代码:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if(strs == null || strs.length == 0){ // 判断是否有这个 strs 存在已经存在了是否为空
return new ArrayList<List<String>>();
}
HashMap<String,List<String>> map = new HashMap<>();
for(String s :strs){
char[] a = s.toCharArray();
Arrays.Sort(a);
String ss = String.valueOf(a); // 将字符数组转换为字符串
if(!map.containsKey(ss)){
map.put(ss,new ArrayList<String>());
}
map.get(ss).add(s);
}
return new ArrayList<List<String>>(map.values());
}
}