래원

[LeetCode] 1790. Check if One String Swap Can Make Strings Equal (Python) 본문

알고리즘/LeetCode

[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 and s2 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