2021-02-11 49. Group Anagrams

49. Group Anagrams

Difficulty: Medium

Related Topics: Hash Table, String

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

Constraints:

  • 1 <= strs.length <= 10<sup>4</sup>
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lower-case English letters.
Solution

Language: Java

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        int[] a = new int[127];
        a['a']=2; a['b']=3; a['c']=5; 
        a['d']=7; a['e']=11; a['f']=13; 
        a['g']=17; a['h']=19; a['i']=23; 
        a['j']=29; a['k']=31; a['l']=37; 
        a['m']=41; a['n']=43; a['o']=47;
        a['p']=53; a['q']=59; a['r']=61; a['s']=67;
        a['t']=71; a['u']=73; a['v']=79;
        a['w']=83; a['x']=89; a['y']=97; a['z']=101;
        
        int[] nums = new int[strs.length];
        
        HashMap<Long, List<String>> hashmap = new HashMap<>();
        
        for (int i = 0; i < strs.length; i++) {
            long result = 2;
            for (int j = 0; j < strs[i].length(); j++) {
                result *= a[strs[i].charAt(j)];
            }
            if (hashmap.containsKey(result)) {
                List<String> list = hashmap.get(result);
                list.add(strs[i]);
                hashmap.put(result, list);
            } else {
                List<String> list = new ArrayList<>();
                list.add(strs[i]);
                hashmap.put(result, list);
            }
        }
        
        List<List<String>> solut = new ArrayList<>();
        
        for (List<String> value : hashmap.values()) {
            solut.add(value);
        }
        
        return solut;
        
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值