알고리즘 스터디

[Leetcode/파이썬] 49. Group Anagrams

난쟁이 개발자 2025. 8. 13. 20:54
반응형

Group Anagrams

Difficulty: Medium


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

 

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]

Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Explanation:

  • There is no string in strs that can be rearranged to form "bat".
  • The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
  • The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.

Example 2:

Input: strs = [""]

Output: [[""]]

Example 3:

Input: strs = ["a"]

Output: [["a"]]

 

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

 

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        group_anagram = defaultdict(list)

        for word in strs :
            sorted_word = ''.join(sorted(word))
            group_anagram[sorted_word].append(word)


        return list(group_anagram.values())

딕셔너리를 활용해서 정렬된 단어가 같은 단어면 word를 추가하는 로직으로 구성하였다. 이번 문제의 변수는 string 정렬을 어떻게 할 것인가. join 메소드를 활용해서 정렬을 할 수 있었다. 

이번 문제는 아나그램의 특성을 잘 이해하고 있다면, 무난히 해결할 수 있는 문제라고 생각한다. 

반응형