###### tags: `Leetcode` `medium` `hash` `python` `Top 100 Liked Questions`
# 49. Group Anagrams
## [題目連結:] https://leetcode.com/problems/group-anagrams/
## 題目:
Given an array of strings ```strs```, group **the anagrams** together. You can return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
```
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
```
**Example 2:**
```
Input: strs = [""]
Output: [[""]]
```
**Example 3:**
```
Input: strs = ["a"]
Output: [["a"]]
```
## 解題想法:
* 題目要求輸出相同字符構成的群組
* 解題技巧:
* 用hash table存
* key: 將strs之item按照字母大小排序好
* value: 原strs之item
* 最終return values()即可.
## Python:
``` python=
from collections import defaultdict
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
map = defaultdict(list)
for item in strs:
#list排序: nums.sort()
#str排序: sorted(str) 排序出來為分開的!!!! 且type為list
#ex: str='eat' sorted(str) = ['a','e','t']
#所以要再合成為單字 作為map的key
map[''.join(sorted(item))].append(item)
return map.values()
if __name__ == '__main__':
result = Solution()
strs = ["eat","tea","tan","ate","nat","bat"]
ans = result.groupAnagrams(strs)
print(ans)
#Input: strs = ["eat","tea","tan","ate","nat","bat"]
#Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
```