크크루쿠쿠

[Leetcode] 49. Group Anagrams 본문

알고리즘

[Leetcode] 49. Group Anagrams

JH_KIM 2021. 6. 12. 22:40

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

 

Group Anagrams - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

Anagram을 판별하는 가장 간단한 방법

-> 단어 자체를 정렬해서 확인하는것.

sorted 함수를 이용한다 ( 문자열도 바로 정렬해줌)

 

ex) "ate","eta","tea" -> "aet",

     "nat","tan","nta" -> "ant"

 

 

 

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        #classify anagrams
        anagrams=collections.defaultdict(list)
        
        #for each strs to anagrams
        for word in strs:
            anagrams[''.join(sorted(word))].append(word)
            
        #return values of anagrams
        return list(anagrams.values())

 

 

Comments