给定一个字符串数组,将字母异位词组合在一起。可以按任意顺序返回结果列表。
字母异位词指字母相同,但排列不同的字符串。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
// 字母与质数对应数组
int[] arr = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101};
HashMap<Long, List<String>> map = new HashMap<>();
int len = strs.length;
for (int i = 0; i < len; i++) {
long sum = 1;
int len2 = strs[i].length();
// 计算乘积
for (int j = 0; j < len2; j++) {
sum *= arr[(strs[i].charAt(j) - 'a')];
}
if(map.containsKey(sum)) {
map.get(sum).add(strs[i]);
}else {
ArrayList<String> strList = new ArrayList<>();
strList.add(strs[i]);
map.put(sum, strList);
}
}
for(Map.Entry<Long, List<String>> s : map.entrySet()) {
res.add(s.getValue());
}
return res;
}
}