Leetcode 49. Group Anagrams
==
### Description
(medium)
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"]]
### 想法
碰到這種一樣字母的又需要裝不只一個value的就可以使用dict,先存一個sorted_str作為比較,判斷使用的字母是否一樣,然後存進去dict中,若是dict中沒有這個key,就創造一個key並帶一個空list,若是有就append進去
照著這樣做就會得到一個dict:
```
str_dic={aet:[eat, tea, ate], ant:[tan, nat], abt:[bat]}
```
### 程式碼
#### python:
```python=
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
str_dic={}
for i in strs:
sorted_i = Solution.tostr(i)
if sorted_i not in str_dic:
str_dic[sorted_i]=[]
str_dic[sorted_i].append(i)
ans=[]
for value in str_dic.values():
ans.append(value)
return ans
def tostr(strs):
return "".join(sorted(strs))
```
Runtime: 135 ms
Memory Usage: 17.2 MB
Your runtime beats 71.72 % of python3 submissions.