Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 분할 정복(Divide and Conquer)
- 큐(Queue)
- DFS & BFS
- DFS
- 플로이드 워셜 알고리즘(Floyd-Warshall Algorithm)
- BFS
- 동적 프로그래밍(Dynamic Programming)
- 백준 2493번
- 다익스트라 알고리즘(Dijkstra Algorithm)
- 백준 2261번
- 백준 1707번
- 스택(Stack)
- BFS(Breadth First Search)
- 백준 17608번
- DFS(Depth First Search)
- 백준 2812번
- 이분 탐색(Binary Search)
- 그리디 알고리즘(Greedy Algorithm)
- 그래프(Graph)
- 백준 21606번
- 알고리즘 개념
- 백준 2504번
- 백준 10000번
- 백준 9012번
- 위상 정렬(Topology Sort)
- 위상 정렬(Topological Sort)
- 이분 그래프(Bipartite Graph)
- 백준 1948번
- 백준 18352번
- 트리(Tree)
Archives
- Today
- Total
Always Be Wise
문자열 조작 : 그룹 애너그램(리트코드 49번) 본문
728x90
▶ 문제 : 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
##### 문제 #####
문자열 배열을 받아 애너그램 단위로 그룹핑하라.
##### 입력 #####
["eat", "tea", "tan", "ate", "nat", "bat"]
##### 출력 #####
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
▶ 접근 방법
애너그램이란 일종의 언어유희로 문자를 재배열하여 다른 뜻을 가진 단어로 바꾸는 것을 말한다.
애너그램을 판단하는 간단한 방법은 정렬하여 비교하는 것이다.
애너그램 관계인 단어들을 정렬하면 서로 같은 값을 갖게 되기 때문이다.
아래 풀이에서는 정렬한 값을 키로하여 단어들을 딕셔너리에 추가한다.
딕셔너리에서 만약 존재하지 않는 키를 삽입하려 할 경우 KeyError가 발생하는데,
이를 방지하기 위해 defaultdict()로 딕셔너리를 선언하면
매번 키 존재 여부를 체크하지 않고 바로 값을 넣을 수 있다.
▶ 풀이 코드
from typing import List
from collections import defaultdict
ex_list = ["eat", "tea", "tan", "ate", "nat", "bat"]
def group_anagrams(strs: List[str]) -> List[List[str]]:
anagrams = defaultdict(list)
for word in strs:
anagrams[''.join(sorted(word))].append(word)
return list(anagrams.values())
print(group_anagrams(ex_list))
###################################################
a = ["cde", "cfc", "abc"]
# 정렬 기준을 문자열의 첫번째와 마지막 글자 기준으로 적용
print(sorted(a, key=lambda s: (s[0], s[-1])))
▶ 관련 링크
2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 유효한 팰린드롬(리트코드 125번)
2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 문자열 뒤집기(리트코드 344번)
2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 로그 파일 재정렬(리트코드 937번)
2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 가장 흔한 단어(리트코드 819번)
'알고리즘 > 리트코드' 카테고리의 다른 글
배열 : 두 수의 합(리트코드 1번) (0) | 2021.12.15 |
---|---|
문자열 조작 : 가장 긴 팰린드롬 부분 문자열(리트코드 5번) (0) | 2021.12.14 |
문자열 조작 : 가장 흔한 단어(리트코드 819번) (0) | 2021.12.14 |
문자열 조작 : 로그 파일 재정렬(리트코드 937번) (0) | 2021.12.14 |
문자열 조작 : 문자열 뒤집기(리트코드 344번) (0) | 2021.12.14 |
Comments