49. Group Anagrams

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 
Return:
[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note: All inputs will be in lower-case.

Solution1: map(str Sort后 -> list)

每个str sort后作为key, 存入map(key -> list(为此key的strs)
n个str,长度m
Time Complexity: O(n * mlogm) Space Complexity: O(n*m)

Solution2:map(str 字母count编码后 -> list)

可以避免str的sort,通过hashmap count 字母个数,来进行编码,如cat becomes 1a1c1t. caabbt becomes 2a2b1c1t,map(码 -> list(为此码的strs)
Time Complexity: O(n * m) Space Complexity: O(n*m)

Solution1 Code:

class Solution1 {
    public List> groupAnagrams(String[] strs) {
        Map> map = new HashMap<>();
        for(String str: strs ) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = String.valueOf(chars);
            if(!map.containsKey(key)) map.put(key, new ArrayList());
            map.get(key).add(str);
        }
        //return new ArrayList>(map.values());
        return new ArrayList<>(map.values());
    }
}

Solution2 Code:

class Solution2 {
    public List> groupAnagrams(String[] strs) {
        HashMap> map = new HashMap<>();
        
        for(String str: strs ) {
            // count
            // if all letters are lower-case
            int[] counter = new int[26];
            for(int j = 0; j < str.length(); j++)
                counter[str.charAt(j) - 'a']++;
            
            // construct the hash from counter
            //Eg: cat becomes 1a1c1t. caabbt becomes 2a2b1c1t
            StringBuilder sb = new StringBuilder("");
            for(int c = 0; c < 26; c++){
                if(counter[c] > 0) {
                    sb.append(counter[c]);
                    sb.append((char) ('a' + c));
                }
            }
            String hash = sb.toString();
            
            //Chech if an entry exists in hash table already, else add a new one
            if(!map.containsKey(hash))
                map.put(hash, new LinkedList());
                
            //Add this string to the list pointed by hash
            map.get(hash).add(str);
        }
        
        return new LinkedList>(map.values());
    }
}

你可能感兴趣的:(49. Group Anagrams)