给定两个由小写字母构成的字符串 A
和 B
,只要我们可以通过交换 A
中的两个字母得到与 B
相等的结果,就返回 true
;否则返回 false
。
示例 1:
输入: A = "ab", B = "ba" 输出: true
示例 2:
输入: A = "ab", B = "ab" 输出: false
示例 3:
输入: A = "aa", B = "aa" 输出: true
示例 4:
输入: A = "aaaaaaabc", B = "aaaaaaacb" 输出: true
示例 5:
输入: A = "", B = "aa" 输出: false
提示:
0 <= A.length <= 20000
0 <= B.length <= 20000
A
和B
仅由小写字母构成。class Solution(object): def buddyStrings(self, A, B): """ :type A: str :type B: str :rtype: bool """ cnt = 0 temp = [] //存储不同的元素 if A == B and len(set(A)) < len(A) : return True if set(A) == set(B): if len(A) == len(B): for i in range(len(A)): if A[i] == B[i]: continue else: temp.append(A[i]) temp.append(B[i]) cnt += 1 else: return False else: return False if cnt == 2: if temp[0] == temp[3] and temp[1] == temp[2]: return True else: return False else: return False