일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 개발자
- realclass
- FIT XR
- 프로젝트
- 읽기
- 뭐든
- 쓰릴오브파이트
- 사이드
- 30분
- Daily Challenge
- 괜찮음
- 리얼 클래스
- 3줄정리
- 화상영어
- Problem Solving
- 미드시청
- 영어원서읽기
- 만화도
- 파비최
- 링피트
- 영어공부
- 매일
- 운동
- English
- 월간
- leetcode
- 10분
- Writing
- 잡생각
- 스탭퍼
Archives
- Today
- Total
파비의 매일매일 공부기록
Today's Challenge 본문
https://leetcode.com/problems/smallest-string-with-swaps
Smallest String With Swaps - 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
DFS나 UnionFind+minHeap으로 풀면 되는 문제라고 한다.
DFS는 익숙한데 UnionFind는 뭔지 모름..
python에서도 dfs는 꽤 쉽게 구현이 되는걸 한 번 더 느낌.
class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
from collections import defaultdict
d = defaultdict(list)
s = list(s)
visited = [False for _ in range(len(s))]
for src, dest in pairs:
d[src].append(dest)
d[dest].append(src)
def dfs(s, i, chars, indices):
if visited[i]:
return
chars.append(s[i])
indices.append(i)
visited[i] = True
for neigh in d[i]:
dfs(s, neigh, chars, indices)
for i in range(len(s)):
if not visited[i]:
chars = []
indices = []
dfs(s, i, chars, indices)
chars = sorted(chars)
indices = sorted(indices)
for c, i in zip(chars, indices):
s[i] = c
return ''.join(s)
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
Today's Challenge (0) | 2022.04.29 |
---|---|
Today's Challenge (0) | 2022.04.28 |
Today's Challenge (0) | 2022.04.26 |
Today's Challenge (0) | 2022.04.25 |
Today's Challenge (0) | 2022.04.24 |
Comments