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

2025. 2. 5. 15:30·알고리즘/LeetCode

 

난이도: 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

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)  (1) 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
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)
  • [LeetCode] 1726. Tuple with Same Product (Python)
  • [LeetCode] 3105. Longest Strictly Increasing or Strictly Decreasing Subarray (Python)
  • [LeetCode] 1752. Check if Array Is Sorted and Rotated (Python)
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    누적합
    이진탐색
    Python
    heapq
    코딩테스트
    Kubernetes
    분산
    아파치 스파크
    programmers
    프로그래머스
    String
    아파치 하둡
    오블완
    우선순위큐
    dfs
    백트래킹
    파이썬
    leetcode
    DP
    알고리즘
    분산처리
    문자열
    티스토리챌린지
    docker
    Apache Spark
    리트코드
    BFS
    쿠버네티스
    도커
    그래프
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 1790. Check if One String Swap Can Make Strings Equal (Python)
상단으로

티스토리툴바