일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 분산
- 프로그래머스
- Kubernetes
- 분산처리
- 알고리즘
- docker
- 리트코드
- 그래프
- Apache Spark
- 아파치 하둡
- leetcode
- programmers
- apache kafka
- 코딩테스트
- Python
- 티스토리챌린지
- 파이썬
- 아파치 카프카
- 오블완
- 하둡
- Apache Hadoop
- heapq
- 이진탐색
- 쿠버네티스
- 도커
- BFS
- 아파치 스파크
- 우선순위큐
- String
- DP
- Today
- Total
래원
[LeetCode] 1790. Check if One String Swap Can Make Strings Equal (Python) 본문
[LeetCode] 1790. Check if One String Swap Can Make Strings Equal (Python)
Laewon Jeong 2025. 2. 5. 15:30
난이도: Easy
문제 설명
You are given two strings s1
and s2
of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return true
if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false
.
문제 예제
Example 1:
Input: s1 = "bank", s2 = "kanb"
Output: true
Explanation: For example, swap the first character with the last character of s2 to make "bank".
Example 2:
Input: s1 = "attack", s2 = "defend"
Output: false
Explanation: It is impossible to make them equal with one string swap.
Example 3:
Input: s1 = "kelb", s2 = "kelb"
Output: true
Explanation: The two strings are already equal, so no string swap operation is required.
제한 사항
1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1
ands2
consist of only lowercase English letters.
Solution(솔루션)
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
if sorted(s1) != sorted(s2):
return False
n = len(s1)
check_diff = 0
for i in range(n):
if s1[i] != s2[i]:
check_diff += 1
if check_diff == 2:
return True
else:
return False
먼저 s1과 s2가 같다고한다면 True를 반환하고, s1과 s2를 정렬시켰을 때 다르다고 한다면 False를 반환했다.
정렬시켰을 때 다르다고 한다면 서로가 가지고 있지 않은 알파벳을 가지고 있어 swap을 해도 같게 되지 못하기 때문이다.
이제 서로 같은 알파벳들만 가지고 있기 떄문에 여기서 각 요소를 비교해본다.
s1[i]가 s[2]와 다르다고 하면 check_diff를 +1 해주었다.
모든 요소를 확인했을 때, check_diff가 2라고 하면 한번에 swap으로 같은 string을 만들 수 있다고 판단하여 True를 return 하였고, 2가 아니라고 한다면 적어도 한번에 swap으로는 해결하지 못한다고 판단하여 False를 return하였다.
문제: 1790. Check if One String Swap Can Make Strings Equal
깃허브: github
algorithmPractice/LeetCode/1915-check-if-one-string-swap-can-make-strings-equal at main · laewonJeong/algorithmPractice
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python) (0) | 2025.02.07 |
---|---|
[LeetCode] 1726. Tuple with Same Product (Python) (0) | 2025.02.06 |
[LeetCode] 3105. Longest Strictly Increasing or Strictly Decreasing Subarray (Python) (0) | 2025.02.03 |
[LeetCode] 1752. Check if Array Is Sorted and Rotated (Python) (0) | 2025.02.02 |
[LeetCode] 3151. Special Array I (Python) (0) | 2025.02.01 |