LeetCode(7), Group Anagrams

Group Anagrams

Description

Given an array of strings, group anagrams together.

Example:

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

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

Solution

1. HashMap and Sorted Array

  • 将每一个string转换成字符数组后,把这个数组按字母顺序排序

  • 新建一个HashMap,key为排序后的字符数组,value为对应的string组成的List

  • 注意: HashMap中的key不可以用字符数组char[],因为数组的hashCode实际上只是该数组的reference。此时,应将char[]再次转换为string,把这个string当做HashMap的key。String is immutable.

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> hashMap = new HashMap<>();
        for (String s : strs) {
            char[] chars = s.toCharArray();
            Arrays.sort(chars);

            String key = new String(chars);
            if (!hashMap.containsKey(key)) hashMap.put(key, new ArrayList());
            hashMap.get(key).add(s);
        }

        return new ArrayList(hashMap.values());
    }
}

Time complexity: O(NlgK), K是字符串的长度, N是数组中字符串的个数。

2. Count Sort

  • 由于所有字符串中只包含26个小写字母,因此在HashMap中的key是一个长度为26的arrayarrayindex对应为该字母在string中出现的次数。

  • HashMap中的value为对应的字符串组成的List

  • 注意: 不可把数组作为HashMap中的key,此时应当将这个数组转换成一个独一无二的数据结构,例如,不相同的数组应该给出不同的key值。

    1. int数组转换成字符串,每一个数字之间用“#”隔开
    2. 直接计算int数组的hashCode,使用Arrays.deepHashCode()
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<Integer, List<String>> hashMap = new HashMap<>();
        
        for (String s : strs) {
            Integer[] alpha = new Integer[26];
            Arrays.fill(alpha, 0);
            for (int i = 0; i < s.length(); i++)
                alpha[s.charAt(i) - 'a']++;
            int key = Arrays.deepHashCode(alpha);
            if (!hashMap.containsKey(key)) hashMap.put(key, new ArrayList());
            hashMap.get(key).add(s);
        }
        return new ArrayList(hashMap.values());
    }
}
  • Time complexity: O(KN), K is 26, which is the size of alphabet. This is a linear solution.
  • Space complexity: O(KN)

3. Unique prime number

  • Use unique prime number for each character in the alphabet. When come to each character, maintain a product, and time the prime number to the product. A string will have a unique integer.
  • This is the fastest method.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值