題目 : 49. Group Anagrams 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"]]
buff : 題目給的list當中的1個字串
buffsorted : 用sorted()重新排列buff字串
solution = {"buffsorted":"buff"}
將buffsorted當作Key,如果有出現過的Key,則在Value中append()buff字串
如果沒有就增加新的Key,assign buff
最後回傳solutions的values即可
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
solution = {}
if len(strs) <1:
return strs
else:
for i in range(len(strs)):
buff = strs[i]
buffsorted = "".join(sorted(buff))
if buffsorted in solution:
solution[buffsorted].append(buff)
else:
solution[buffsorted] = [buff]
return solution.values()