给定两个由小写字母构成的字符串 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 仅由小写字母构成。
def buddyStrings(A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if not A or not B:
return False
if len(A)!=len(B):
return False
temp=[]
counter=0
C=dict(zip(A,B))
#print(C)
for k in C:
if k!=C[k]:
temp.append(k)
temp.append(C[k])
counter+=1
if counter==0:
if len(list(set(A))) < len(A):
return True
else:
return False
elif counter==2:
if temp[0]==temp[3] and temp[2]==temp[1]:
return True
else:
return False
else:
return False
print('A = "ab", B = "ba"',buddyStrings("ab","ba"))
print('A = "ab", B = "ab"',buddyStrings("ab","ab"))
print('A = "aa", B = "aa"',buddyStrings("aa","aa"))
print('A = "aaaaaaabc", B = "aaaaaaacb"',buddyStrings("aaaaaaabc","aaaaaaacb"))
print('A = "", B = "aa"',buddyStrings("","aa"))