nathanwailes

LeetCode 49 - Group Anagrams - 2022.12.19 solution

Sep 30th, 2023
1,117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.61 KB | None | 0 0
  1.     def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
  2.         # An anagram is defined by the set of characters in it.  And when I hear "group these elements" I immediately think of having a dict with keys defining the groups and the values being lists or sets of elements.  So I'm going to have a dict that maps from a set of characters to a list of strings that have that set of characters.
  3.         from collections import defaultdict
  4.         chars_to_words = defaultdict(list)
  5.         for item in strs:
  6.             chars_to_words[tuple(sorted(item))].append(item)
  7.         return chars_to_words.values()
Advertisement
Add Comment
Please, Sign In to add comment