49. 字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母都恰好只用一次。
- 示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
- 示例 2:
输入: strs = [""]
输出: [[""]]
- 示例 3:
输入: strs = [“a”]
输出: [[“a”]]
解题思路
使用将单词中每个字符以及其对应的出现的次数拼接成为key
代码
class Solution {public List<List<String>> groupAnagrams(String[] strs) {Map<String,List<String>> map=new HashMap<>();for(String s:strs){int[] cnt=new int[26];for(int i=0;i<s.length();i++)cnt[s.charAt(i)-'a']++;StringBuilder sb=new StringBuilder();for(int i=0;i<26;i++)if(cnt[i]>=0)sb.append((char)(i+'a')).append(cnt[i]);String temp=sb.toString();if(!map.containsKey(temp))map.put(temp,new ArrayList<>());map.get(temp).add(s);}List<List<String>> res=new ArrayList<>();for(List l:map.values())res.add(l);return res;}
}