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)
'다전공_컴퓨터공학 > 알고리즘 문제풀이' 카테고리의 다른 글
[파이썬 알고리즘] 7장 배열 - 두 수의 합 (two-sum) (0) | 2020.11.13 |
---|---|
[파이썬 알고리즘] 6장 - 문자열 조작 (longest palindrome substring) ⭐ (0) | 2020.11.03 |
[파이썬 알고리즘] 6장 - 문자열 조작 (most common word) (0) | 2020.11.03 |
[파이썬 알고리즘] 6장 - 문자열 조작 (recorder log files) (0) | 2020.11.02 |
[파이썬 알고리즘] 6장 - 문자열 조작 (valid palindrome) (0) | 2020.11.02 |