给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
示例 1:示例 2:输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 3:输入: strs = [“”]
输出: [[“”]]
提示:输入: strs = [“a”]
输出: [[“a”]]
- 1 <= strs.length <= 104
- 0 <= strs[i].length <= 100
- strs[i] 仅包含小写字母
如果两个字符串再根据字符进行排序后,得到的字符串相等,那么这两个字符串为字母异位词。
使用HashMap,提高存取效率。
Map> map = new HashMap >(); public List > groupAnagrams(String[] strs) { for(int i = 0; i < strs.length; i++) { char[] chs = strs[i].toCharArray(); Arrays.sort(chs); if(map.containsKey(new String(chs))) { map.get(new String(chs)).add(i); } else { List
lis = new ArrayList (); lis.add(i); map.put(new String(chs), lis); } } List > res = new ArrayList
>(); for(List
lis: map.values()) { List tmp = new ArrayList (); for(int ind: lis) tmp.add(strs[ind]); res.add(tmp); } return res; }



