LeetCode49 -Group Anagrams

문이월·2022년 7월 26일

Algorithm

목록 보기
4/11

leetcode 49

string type 배열을 받아 anagram 단위로 grouping 하는 문제.

Anagram이란 문자를 재배열하여 다른 뜻을 가진 단어로 바꾸는 것을 말한다.

단어를 sorting하여 비교하면 쉽게 풀 수 있다.

sort()와 sorted()의 차이

sort()는 제자리에서 정렬하고 list만 수정 가능하다. sorted()는 새 목록을 반환하고 모든 이터러블이 사용 가능하다.

colletions.defaultdict

default type을 지정할 수 있어서 KeyError를 방지할 수 있다.

import collections

class Solution:
    def groupAnagrams(self, strs):
        anagrams = collections.defaultdict(list)
        
        for word in strs:
            anagrams[''.join(sorted(word))].append(word)
            
        return anagrams.values()
profile
ㅋㅅㅋ

0개의 댓글