|
| 1 | +""" |
| 2 | +Problem: |
| 3 | +----------------------------------------------- |
| 4 | +https://leetcode.com/problems/group-anagrams |
| 5 | +
|
| 6 | +
|
| 7 | +HashMap Solution: |
| 8 | +----------------------------------------------- |
| 9 | +@description: |
| 10 | +We can group the anagrams in a hashmap |
| 11 | +where we create a key representing their letters sorted. |
| 12 | +
|
| 13 | +Actually, designing a key is to build a mapping relationship by yourself |
| 14 | +between the original information and the actual key used by hash map. |
| 15 | +When you design a key, you need to guarantee that: |
| 16 | +1. All values belong to the same group will be mapped in the same group. |
| 17 | +2. Values which needed to be separated into different groups will not be mapped into the same group. |
| 18 | +
|
| 19 | +This process is similar to design a hash function, but here is an essential difference. |
| 20 | +A hash function satisfies the first rule but might not satisfy the second one. |
| 21 | +But your mapping function should satisfy both of them. |
| 22 | +
|
| 23 | +In the example above, our mapping strategy can be: |
| 24 | +sort the string and use the sorted string as the key. |
| 25 | +That is to say, both "eat" and "ate" will be mapped to "aet". |
| 26 | +
|
| 27 | +Input: strs = ["eat","tea","tan","ate","nat","bat"] |
| 28 | +Output: [["bat"],["nat","tan"],["ate","eat","tea"]] |
| 29 | +
|
| 30 | +["eat","tea","tan","ate","nat","bat"] |
| 31 | +
|
| 32 | +key value |
| 33 | +["aet"] - ["eat","tea", "ate"] |
| 34 | +["ant"] - ["nat","tan"] |
| 35 | +["abt"] - ["bat"] |
| 36 | +
|
| 37 | +@complexity: |
| 38 | +Time: O(n*klogk), where n is the number of anagrams and k is the max_len_anagram out of them |
| 39 | +Space: O(n), for the hashmap of all strings with no repetition + the sorted versions of each anagram as keys |
| 40 | +""" |
| 41 | +class Solution: |
| 42 | + def groupAnagrams(self, strs): |
| 43 | + if len(strs) == 0: |
| 44 | + return [[""]] |
| 45 | + |
| 46 | + hash_map = {} |
| 47 | + |
| 48 | + for s in strs: |
| 49 | + key = ''.join(sorted(s)) |
| 50 | + if key in hash_map: |
| 51 | + hash_map.get(key).append(s) |
| 52 | + else: |
| 53 | + hash_map[key] = [s] |
| 54 | + |
| 55 | + return hash_map.values() |
| 56 | + |
0 commit comments