PS/LeetCode

[LeetCode] 49.Group Anagrams

램램 2023. 1. 18. 03:48

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


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.

defaultdict - key 값으로 묶기

defaultdict를 이용하여 동일한 key 값을 가진 string들 끼리 묶일 수 있도록 한다.
애너그램은 정렬했을 때 같은 문자가 되는 문자들이기 때문에 각 단어를 알파벳 순으로 정렬한 값을 key 값으로 정하는 게 가장 간단하다.

def groupAnagrams(strs):
  anagram = collections.defaultdict(list)

  for word in strs:
      key = ''.join(sorted(word))
      # sorted()는 문자열도 리스트 형태로 리턴하므로 join을 이용하여 다시 string으로 바꿔줌
      
      anagram[key].append(word)
      # dict_items([('aet', ['eat', 'tea', 'ate']), ('ant', ['tan', 'nat']), ('abt', ['bat'])])

  return list(anagram.values()) # defaultdict의 value 값들만 리턴