049 字母异位词分组
题目:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
方法:用hashmap的特性
思路:创建一个hashmap<String,List>,然后把String转换成数组进行排序,然后转换成String进行判断是否是字母异位词,如果是就加入这个List,不是就创建一个,加入新的,并放入hashmap中,最后将hashmap中的放在List中去
代码:
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> list = new ArrayList<>();
Map<String,List<String>> map = new HashMap<>();
for (int i = 0; i <strs.length ; i++) {
//判断是否重复
char[] c =strs[i].toCharArray();
Arrays.sort(c);
String s = new String(c);
if(map.containsKey(s)){
List<String> p=map.get(s);
p.add(strs[i]);
map.put(s,p);
}else{
List<String> p= new ArrayList<>();
p.add(strs[i]);
map.put(s,p);
}
}
list.addAll(map.values());
return list;
}