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;}
}