일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 미드시청
- 쓰릴오브파이트
- Writing
- 운동
- English
- 프로젝트
- FIT XR
- 월간
- 뭐든
- 사이드
- 만화도
- 링피트
- 리얼 클래스
- 영어공부
- realclass
- 화상영어
- 읽기
- 영어원서읽기
- 파비최
- leetcode
- Problem Solving
- 3줄정리
- 30분
- 잡생각
- Daily Challenge
- 10분
- 매일
- 개발자
- 괜찮음
- 스탭퍼
Archives
- Today
- Total
파비의 매일매일 공부기록
2023.04.28 Today's Challenge 본문
https://leetcode.com/problems/similar-string-groups/
Similar String Groups - LeetCode
Can you solve this real interview question? Similar String Groups - Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal. For example, "tars
leetcode.com
Union-Find 기법 사용.
소스가 좀 긴 편이다.
class Solution:
def numSimilarGroups(self, strs: List[str]) -> int:
UF = {}
ranks = defaultdict(int)
def find(x):
if x not in UF:
UF[x] = x
if x != UF[x]:
UF[x] = find(UF[x])
return UF[x]
def union(x, y):
rx, ry = find(x), find(y)
if ranks[rx] < ranks[ry]:
UF[rx] = ry
return
UF[ry] = rx
if ranks[rx] == ranks[ry]:
ranks[rx] += 1
def are_nei(a, b):
dif = 0
for i in range(len(a)):
if a[i] != b[i]:
dif += 1
return dif == 0 or dif == 2
for i in range(len(strs)):
for j in range(i+1, len(strs)):
if are_nei(strs[i], strs[j]):
union(strs[i], strs[j])
return len(set([find(x) for x in strs]))
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
2023.04.30 Today's Challenge (0) | 2023.04.30 |
---|---|
2023.04.29 Today's Challenge (0) | 2023.04.29 |
2023.04.27 Today's Challenge (0) | 2023.04.27 |
2023.04.26 Today's Challenge (0) | 2023.04.26 |
2023.04.25 Today's Challenge (0) | 2023.04.25 |
Comments