Given two strings A
and B
of lowercase letters, return true
if and only if we can swap two letters in A
so that the result equals B
.
Input: A = "ab", B = "ba" Output: true
Input: A = "ab", B = "ab" Output: false
Input: A = "aa", B = "aa" Output: true
Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true
Input: A = "", B = "aa" Output: false
0 <= A.length <= 20000
0 <= B.length <= 20000
A
andB
consist only of lowercase letters.
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
if A == B and len(set(A)) != len(A):
return True
a, b = '', ''
for k, v in enumerate(A):
if v != B[k]:
a += v
b += B[k]
if len(a) > 2:
return False
return len(a) == 2 and a == b[::-1]