49. Group Anagrams

Seong-Soo Jeong·2021년 4월 9일
post-thumbnail

문제

주어진 문자열 배열 strs애너그램별로 그룹화하라.

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"]]


풀이

'eat'와 'ate'는 애너그램이다. 같은 문자들로 이루어져 있기 때문에, 단어를 이루는 문자들을 사전 순서대로 정렬하게 되면, 같은 결과가 나오게 된다. 따라서 이 문제는 단어를 이루는 문자들을 사전 순서 대로 정렬 한 후, 정렬 순서대로 이어 붙인 단어를 key로 하고, 같은 값을 가지는 단어들의 list를 value로 하는 dictionary를 이용하면 쉽게 풀 수 있다.

from collections import defaultdict

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        str_dict = defaultdict(list)
	
        for word in strs:
            str_dict[''.join(sorted(word))].append(word)

        return str_dict.values()
profile
Man in the middle

0개의 댓글