给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
用map纪录res中对应元素如ate所在list的索引,当有ate的异位词出现时,初始化list,并且把已出现的它的异位词加入到list,然后把该词加进去。
1 class Solution { 2 public List<List<String>> groupAnagrams(String[] strs) { 3 List<List<String>> res = new ArrayList<>(); 4 if(strs == null || strs.length == 0) return res; 5 HashMap<String,Integer> map = new HashMap<>(); 6 for(String str : strs){ 7 char[] ch = str.toCharArray(); 8 Arrays.sort(ch); 9 String s = new String(ch); 10 if(map.containsKey(s)){ 11 List<String> list = res.get(map.get(s)); 12 list.add(str); 13 }else{ 14 List<String> list = new ArrayList<>(); 15 list.add(str); 16 map.put(str,res.size()); 17 res.add(list); 18 } 19 } 20 return res; 21 } 22 23 }