# 05. 그룹 애너그램(leetcode: 49)

{% hint style="info" %}
[**문제링크**](https://leetcode.com/problems/group-anagrams/submissions/)

[**defaultdict 사용법**](https://dongdongfather.tistory.com/69)

[**공식 docs**](https://docs.python.org/3.3/library/collections.html#collections.defaultdict)
{% endhint %}

## 분석

[**애너그램이란?**](https://namu.wiki/w/%EC%95%A0%EB%84%88%EA%B7%B8%EB%9E%A8?from=%EC%95%84%EB%82%98%EA%B7%B8%EB%9E%A8)

결국 문자열의 리스트에서 **같은 애너그램을 만드는 문자** 들을 찾고, 해당 문자들을 리스트의 리스트로 만드는게 문제의 핵심

인자로 들어온 `strs` (리스트) 를 순회하면서

1. 정렬된 문자열 `sorted_s` 를 만든다.
2. `sorted_s` 를 `key` 로 하는 해쉬의 `value` 로 `str` 을 넣는다.

2번에서 `value`로 str 을 넣는다고 했는데, 여기서 일반적인 딕셔너리를 사용해서는 문제를 해결할 수도 없다.

왜냐하면 `value` 의 형태는 `str` 이 복수가 들어가는 **리스트** 여야 하는데, 일반적인 dict 로는 list를 넣는 방법이 애매하고 무엇보다도 **초기값 때문에 문제가 생긴다.**

**defaultdict 를 사용하면 비어있는 key 에 value 를 넣으면 default 로 값을 생성한다!!!**

## 풀이

```python
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dict = collections.defaultdict(list)
        for s in strs:
            dict[''.join(sorted(s))].append(s)
        return dict.values()
```

여기서 눈여겨 볼건 **defaultdict** 의 활용법이다. 이게 빛을 발하는건 5번 째 줄에있는 `dict[''.join(sorted(s))].append(s)` 에서다. 만약 key 값이 없는데, append 메서드를 호출하면 어떻게 될까? 일반적인 dict 였다면 **out of range** 에러가 발생했겠지만, **defaultdict은 기본값으로 비어있는 리스트를 만들고 그 메서드를 실행한다!!**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://simian114.gitbook.io/blog/undefined/undefined-1/05.-leetcode-49.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
