49. Group Anagrams

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.

My Solutions:

方法1:

把 str转换成chars,然后用sorted chars当hashmap里的key,value是所有anagram的str。

    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> list = new ArrayList<>();
        
        if (strs == null || strs.length == 0) return list;
        
        HashMap<String, ArrayList<String>> map = new HashMap<>();
        for (String s : strs) {
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<String>());
            }
            map.get(key).add(s);
        }
        
        return new ArrayList<List<String>>(map.values());
    }
  • Time Complexity: O(NK logK), where N is the length of strs, and K is the maximum length of a string in strs. The outer loop has complexity O(N)as we iterate through each string. Then, we sort each string in O(K logK) time.

  • Space Complexity: O(NK), the total information content stored in map.

方法2:

把每个str里字符的出现频率记在一个int array里。用一个StringBuilder做一个字母+频率形式的string,如果这个string出现在map中,说明anagram的str出现

    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList();
        Map<String, List> ans = new HashMap<String, List>();
        int[] count = new int[26];
        for (String s : strs) {
            Arrays.fill(count, 0); // reset the count array for each word
            for (char c : s.toCharArray()) count[c - 'a']++;

            StringBuilder sb = new StringBuilder("");
            for (int i = 0; i < 26; i++) {
                sb.append(count[i]);
                sb.append((char) ('a' + i));
            }
            String key = sb.toString();
            if (!ans.containsKey(key)) ans.put(key, new ArrayList());
            ans.get(key).add(s);
        }
        return new ArrayList(ans.values());
    }
  • Time Complexity: O(NK) where N is the length of strs, and K is the maximum length of a string in strs. Counting each string is linear in the size of the string, and we count every string.

  • Space Complexity: O(NK), the total information content stored in ans.

Last updated