给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入:["eat", "tea", "tan", "ate", "nat", "bat"]
, 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
class Solution { public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> lists = new ArrayList<>(); if(strs == null || strs.length == 0){ return lists; } Map<String,List<String>> map =new HashMap<>(); for(int i = 0;i < strs.length;i++){ char[] chars = strs[i].toCharArray(); Arrays.sort(chars); String s = new String(chars); if(!map.containsKey(s)){ map.put(s,new ArrayList<String>()); } map.get(s).add(strs[i]); } return new ArrayList<>(map.values()); } }
原文:https://www.cnblogs.com/zzytxl/p/12667052.html