49. Group Anagrams Python3

Yelim Kim·2021년 9월 14일
0
post-thumbnail

Problem

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

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

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.

My code

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

Review

실행 결과 : Runtime(108ms), Memory(17.9MB)

[접근법]
각 단어를 알파벳순으로 나열한 다음에 딕셔너리에 저장하기
이렇게 되면 같은 단어는 저절로 중복으로 간주되어 한번만 저장되고 다른 값은 다른 key값에 저장된다.
value를 출력

[느낀점]
머리속으로는 엄청 복잡했던 게 코드로 이렇게 간단하게 나타낼 수 있다니... 이런저런 친구들과 많이 친해져야겠다.

profile
뜬금없지만 세계여행이 꿈입니다.

1개의 댓글

comment-user-thumbnail
2021년 12월 30일

I found that solution very popular and helpful:
https://www.youtube.com/watch?v=n80QtzugEP8&ab_channel=EricProgramming

답글 달기