관리 메뉴

솜씨좋은장씨

[leetCode] 859. Buddy Strings (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 859. Buddy Strings (Python)

솜씨좋은장씨 2020. 11. 12. 00:20
728x90
반응형

Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad".

 

Example 1:

Input: A = "ab", B = "ba"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.

Example 2:

Input: A = "ab", B = "ab"
Output: false
Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.

Example 3:

Input: A = "aa", B = "aa"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.

Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true

Example 5:

Input: A = "", B = "aa"
Output: false

 

Constraints:

  • 0 <= A.length <= 20000
  • 0 <= B.length <= 20000
  • A and B consist of lowercase letters.

Solution

class Solution:
    def buddyStrings(self, A: str, B: str) -> bool:
        if len(A) != len(B):
            return False
        else:
            list_A = list(A)
            list_B = list(B)
            
            check_string_A = []
            check_string_B = []
            
            
            for i in range(len(list_A)):
                if list_A[i] != list_B[i]:
                    check_string_A.append(list_A[i])
                    check_string_B.append(list_B[i])
                    
                    if len(check_string_A) > 2:
                        return False
            if len(check_string_A) == 2 and check_string_A[::-1] == check_string_B:
                return True
            
            if len(check_string_A) == 0:
                if len(list_A) > len(set(list_A)):
                    return True
                return False

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments