본문 바로가기
LeetCode/Problems

LeetCode 49. Group Anagrams

by 벤진[Benzene] 2020. 8. 19.

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]

댓글