很有意思的一道题目,一看就会,一写就废~~~
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母都恰好只用一次。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
1)将相同的字符串放入到同一集合,这里可以用Map,Map的key针对一组字母具有唯一性,比如abc与bac的key需要相等。
2)如何判断字母异位就是难点了,想到了以下几种方法
方法一:利用乘法交换律(a*b=b*a)保证交换位置结果不变,从而判断是字符串所组成的字母是否为同一组。 定义一个字母与质数的对应关系,其数的积作为Map的key存储,相同的key为一组存放到同一个List里。
class Solution {
/**
* 字母异位词
* 用质数表示26个字母,把字符串的各个字母相乘
*/
public static List> groupAnagrams(String[] strs) {
List> group = new ArrayList<>();
//用质数表示26个字母
int[] primeNumberList = {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};
//如果可以返回Collection> 就不需要转换,可节省存储空间
Map> result = new HashMap<>(strs.length);
List stringList;
for (String str : strs) {
if (str == null || str.length() < 1) {
stringList = result.containsKey(0) ? result.get(0) : new ArrayList<>();
stringList.add(str);
result.put(0, stringList);
continue;
}
//product=质数乘机,利用乘法交换律,顺序改变,结果不变
int product = 1;
for (int i = 0; i < str.length(); i++) {
product = product * primeNumberList[str.charAt(i) - 'a'];
if(product==0){product=103;}
}
stringList = result.containsKey(product) ? result.get(product) : new ArrayList<>();
stringList.add(str);
result.put(product, stringList);
}
group.addAll(result.values());
return group;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。