49. Group Anagrams

Description

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.

Solution

HashMap, time O(n * logk), space O(n)

class Solution {
    public List> groupAnagrams(String[] strs) {
        List> groups = new LinkedList<>();
        if (strs == null) {
            return groups;
        }
        
        Map> map = new HashMap<>();
        for (String s : strs) {
            String sorted = sort(s);
            if (!map.containsKey(sorted)) {
                map.put(sorted, new LinkedList<>());
            }
            map.get(sorted).add(s);
        }
        
        groups.addAll(map.values());
        return groups;
    }
    
    public String sort(String s) {
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
}

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