Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
- # 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.
- from collections import defaultdict
- chars_to_words = defaultdict(list)
- for item in strs:
- chars_to_words[tuple(sorted(item))].append(item)
- return chars_to_words.values()
Advertisement
Add Comment
Please, Sign In to add comment