Group Anagrams - 그룹 단어

임명수·2022년 7월 9일
0

파이썬 알고리즘

목록 보기
5/5
post-thumbnail

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.

python3

import collections
import re
from typing import List

class Solution:
     def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        anagrams = collections.defaultdict(list)

        for word in strs:
            anagrams[''.join(sorted(word))].append(word)

        return anagrams.values()코드를 입력하세요

[문제해결]

collections.defaultdict는 딕셔너리(dictionary)와 거의 비슷하지만 key값이 없을 경우 미리 지정해 놓은 초기(default)값을 반환하는 dictionary이다
[참고사이트]
https://excelsior-cjh.tistory.com/95

1.list를 담을 anagrams 딕셔너리를 만든다(default값 있는 딕셔너리)
2.문자열을 정렬하고 같은것이 모인 것을 추가한 것을 anagrams 딕셔너리에 담는다
3.anagrams 딕셔너리의 value 값 반환

실용적인 면은 음...
문자열 rearrange한다하는데 사실상 알파벳에서만 유용할수 있을듯하고
알파벳 유희나.. 암호화 밖에 생각나지 않는다.

profile
푸른영혼의별

0개의 댓글