Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import defaultdict
- class Solution:
- def groupAnagrams(self, strs):
- # Initialize a defaultdict to store anagrams grouped by their sorted forms
- hashset = defaultdict(list)
- # Loop through each string in the input list
- for s in strs:
- # Sort the characters in the string and join them to form the sorted string
- sorted_str = ''.join(sorted(s))
- # Append the original string to the list associated with its sorted form
- hashset[sorted_str].append(s)
- # Return a list of grouped anagram lists
- return list(hashset.values())
Advertisement
Add Comment
Please, Sign In to add comment