-
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.
For two words to be anagrams, their sorted version will be equal. For example "bat" and "tab" will both become "abt" after sorted. Therefore we can use the sorted version as keys for an dicitionary and use that dictionary to record the strings.
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups=defaultdict(list)
for i in strs:
temp="".join(sorted(i))
groups[temp].append(i)
return groups.values()