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

 

<문제>

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.

 

<예시>

Input: strs = ["eat","tea","tan","ate","nat","bat"]

Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

 

Input: strs = ["a"]

Output: [["a"]]

 


# https://leetcode.com/problems/group-anagrams/
from collections import defaultdict


def solution_1(strs: list):
    anagrams = defaultdict(list)
    for str in strs:
        set_str = "".join(sorted(list(str)))
        anagrams[set_str].append(str)
    return list(anagrams.values())

 

 

<알게된 것>

* sorted / sort

  • sorted -> 정렬된 객체를 리턴
  • sort -> 정렬 수행하여 제자리 정렬 (in-place sort)
  • sorted에서는 key 지정 가능
    • ex1) sorted(list, key=len)
    • ex2) sorted(list, key=lambda x:x[0], x[1]) 
    • ...

* 파이썬 team sort 사용

  • 최선의 경우에는 O(n)

 

+ Recent posts