Group anagrams - leetcode(49)

llama·2022년 3월 13일

알고리즘

목록 보기
9/16
post-thumbnail

Group anagrams

요구사항

  • Given an array of strings strs, group the anagrams together. You can return the answer in any order.
    => 입력받은 배열을 같은 애너그램끼리 그룹화 시킨다.

Anagram 이란

한 단어의 철자를 분해하여 다른 단어 혹은 다른 문장으로 바꾸는것을 의미한다.
ex) Enough => Huge No!


Solution

import collections

preInput = ["eat","tea","tan","ate","nat","bat"]

class Solution:
    def groupAnagrams(self, strs):
     	# 존재하지 않는 키에 삽입하는 경우 KeyError가 나는것을 방지하기 위해 초기값을 할당해준다.
        # 기본값이 list이기 때문에 append가 사용가능 하다.
        anagrams = collections.defaultdict(list)

        for word in strs:
        	# dict에 정렬된 단어를 키로 넣고, 값으로 원래 단어를 넣는다.
            anagrams["".join(sorted(word))].append(word)
            
            # List 길이순으로 정렬해줬다.
        return sorted(list(anagrams.values()), key=len)

sol = Solution()

print(a.groupAnagrams(preInput))
# >>> [['bat'], ['tan', 'nat'], ['eat', 'tea', 'ate']]

📌 코드 풀이

  1. for문으로 입력값을 돌려서 단어를 정렬하고, 해당 값을 키로 이용하여 딕셔너리에 단어들을 넣어준다.
  2. 딕셔너리에 존재하지 않는 키를 삽입하는 경우 KeyError가 발생하는것을 방지하기 위해 collections - defaultdict(list)로 만들고, 1번을 이용해준다.
    => 초기 값이 list이기 때문에 append를 이용할 수 있다.
  3. 2번의 dict.values()로 값만 추출하여 list로 만들어서 반환하면 된다.

leetcode

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

profile
요리사에서 프론트엔드 개발자를 준비하는중 입니다.

0개의 댓글