Problem:
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
Summary:
1. Create a defaultdict(list) to save the sorted word as a key in list format.
2. For each word, sort the word so that any anagram word would be saved in a list under same key.
3. return with all values saved in a dictionary.
Code:
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = collections.defaultdict(list)
for word in strs:
anagrams[''.join(sorted(word))].append(word)
return anagrams.values()
https://www.w3schools.com/python/ref_string_join.asp
Python String join() Method
Python String join() Method ❮ String Methods Example Join all items in a tuple into a string, using a hash character as separator: myTuple = ("John", "Peter", "Vicky") x = "#".join(myTuple) print(x) Try it Yourself » Definition and Usage The join() meth
www.w3schools.com
모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]
'LeetCode > Problems' 카테고리의 다른 글
LeetCode 15. 3Sum [Medium] (0) | 2020.08.25 |
---|---|
LeetCode 42. Trapping Rain Water [Hard] (1) | 2020.08.24 |
LeetCode 819. Most Common Word (0) | 2020.08.18 |
LeetCode 937. Reorder Data in Log Files (0) | 2020.08.17 |
LeetCode 628. Maximum Product of Three Numbers (0) | 2020.07.09 |
댓글