给定一个字符串数组 strs
,将 变位词 组合在一起。 可以按任意顺序返回结果列表。
注意:若两个字符串中每个字符出现的次数都相同,则称它们互为变位词。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i]
仅包含小写字母
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> resultMap = new HashMap<>();
for (String str : strs) {
String key = generateKey(str);
resultMap.putIfAbsent(key, new ArrayList<>());
resultMap.get(key).add(str);
}
return new ArrayList<>(resultMap.values());
}
private String generateKey(String str) {
int[] alpha = new int[26];
StringBuilder sBuilder = new StringBuilder();
for (char ch : str.toCharArray()) {
alpha[ch - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (i > 0) {
sBuilder.append("-");
}
sBuilder.append(alpha[i]);
}
return sBuilder.toString();
}
}
//leetcode submit region end(Prohibit modification and deletion)