본문 바로가기

Algorithm/Leetcode

[Top Interview 150 - Hashmap] 49. Group Anagrams

[Q] [Medium]

Given an array of strings strs, group the anagrams together. 
You can return the answer in any order.

 

  • 일단 문제가 짧아서 좋았다 22..
  • collections.defaultdict 함수 쓰면 아주 간단하게 해결되는데 참고한 문제 해결 방법이 독특해서 재밌었다.
# Answer

import collections

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 list(anagrams.values())