这题比较巧妙,将字符串中的每个字符赋以
hash质数
对字符串中的每个值可以乘以对应的质数,若发现最终的乘积结果相等,则字符串为对应的易伟慈分组,利用到hashMap
的变相处理方法
/*** @Author zhoujian* @Date 2020/8/20 8:55字母的异位词分组自定义字符串的哈希规则,使用质数作为乘法因子(Java)
/*/
public class Problem49 {public List<List<String>> groupAnagrams(String[] strs) {// 考察了哈希哈数的基本知识,zhiyao26个即可// key就是下标,value就是数值int[] primes = {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};// key是字符串自定义规则下的哈希值Map<Integer,List<String>> hashMap = new HashMap<>();for(String s:strs){int hashValue = 1;char[] charArray = s.toCharArray();for(char c:charArray){hashValue*=primes[c-'a'];}// 吧单词添加到哈希值相同的分组ainsKey(hashValue)){List<String> curList = (hashValue);curList.add(s);}else{List<String> newList = new ArrayList<>();newList.add(s);hashMap.put(hashValue,newList);}}return new ArrayList<>(hashMap.values());}
本文发布于:2024-01-28 05:08:22,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063897085007.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |