m1ndy5's coding blog

LeetCode 49. Group Anagrams with Python 본문

알고리즘 with python/알고리즘 스터디

LeetCode 49. Group Anagrams with Python

정민됴 2024. 1. 3. 17:24

https://leetcode.com/problems/group-anagrams/

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dic = {}
        for word in strs:
            # 알파벳 순으로 정렬(ate -> aet)
            w = ''.join(sorted(word))
            if w not in dic:
                dic[w] = [word]
            else:
                dic[w].append(word)

        return list(dic.values())

Python sorted

병합 정렬 + 삽입 정렬 아이디어를 더한 하이브리드 방식
O(NlogN)의 시간복잡도를 가짐
정렬된 결과를 리스트 자료형으로 반환한다.