49. Group Anagrams

https://leetcode.com/problems/group-anagrams/submissions/

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.

Thoughts

给一些单词,让把出现相同字符的单词放在一组。判断是否permutation除了用count map检测每个元素是否都在, 还可以用 sorting配合hash table。

Code

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        m = collections.defaultdict(list)
        for s in strs:
            # m[''.join(sorted(s))].append(s)
            cnt = [0] * 26
            for c in s:
                cnt[ord(c) - ord('a')] += 1
            m[tuple(cnt)].append(s)
        return m.values()
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] cs = str.toCharArray();
            Arrays.sort(cs);
            String keyStr = String.valueOf(cs);
            if (map.containsKey(keyStr)) {
                map.get(keyStr).add(str);
            } else {
                map.put(keyStr, new ArrayList<>());
                map.get(keyStr).add(str);
            }
        }
        List<List<String>> res = new ArrayList<>();
        for (String str : map.keySet()) {
            res.add(map.get(str));
        }
        return res;
    }
}

Analysis

时间复杂度O(nlgn).

Last updated