给定两个由小写字母构成的字符串 A
和 B
,只要我们可以通过交换 A
中的两个字母得到与 B
相等的结果,就返回 true
;否则返回 false
。
示例 1:
输入: A = "ab", B = "ba" 输出: true
示例 2:
输入: A = "ab", B = "ab" 输出: false
class Solution(object): def buddyStrings(self, A, B): """ :type A: str :type B: str :rtype: bool """ count = 0 dict_1 = {} A_list = [] B_list = [] if len(A) != len(B): return False elif len(A) == 0 or len(B) == 0: return False elif A == B: for i in A: if i in dict_1: dict_1[i] += 1 else: dict_1[i] = 1 for k,v in dict_1.items(): if v>=2: return True return False elif len(A) == len(B): for i in range(len(A)): if A[i] != B[i]: count += 1 A_list.append(A[i]) B_list.append(B[i]) if count == 2 and sorted(A_list) == sorted(B_list): return True else: return False