分销pc网站,wordpress 多站点主题,wordpress 插件翻译,开公司流程及费用49. 字母异位词分组
给你一个字符串数组#xff0c;请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词#xff0c;所有源单词中的字母都恰好只用一次。
示例 1:
输入: strs [“eat”, “tea”, “tan”…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 ListListString groupAnagrams(String[] strs) {MapString,ListString mapnew HashMap();for(String s:strs){int[] cntnew int[26];for(int i0;is.length();i)cnt[s.charAt(i)-a];StringBuilder sbnew StringBuilder();for(int i0;i26;i)if(cnt[i]0)sb.append((char)(ia)).append(cnt[i]);String tempsb.toString();if(!map.containsKey(temp))map.put(temp,new ArrayList());map.get(temp).add(s);}ListListString resnew ArrayList();for(List l:map.values())res.add(l);return res;}
}