[leetcode] group-anagrams

hodu·2023년 1월 23일
0

algorithm

목록 보기
27/27

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

그룹 애너그램 문제이다.

(책에서 힌트를 얻었음)

  1. 문자를 알파벳 단위로 "정렬"한다.
    "eat", "ate" 는 정렬하면 모두 "aet"이다.
  2. 정렬한 값이 같은 문자열을 "딕셔너리"의 value 값으로 넣어주면 된다.
    {"ate" : ["eat", "ate"]}
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dict_strs = {}
        for i in strs:
            dict_strs[''.join(sorted(i))] = []

        for j in strs:
            dict_strs[''.join(sorted(j))].append(j)

        return [*dict_strs.values()]
profile
안녕 세계!

0개의 댓글