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.
Example 1:
Input: A = “ab”, B = “ba”
Output: true
Example 2:
Input: A = “ab”, B = “ab”
Output: false
Example 3:
Input: A = “aa”, B = “aa”
Output: true
Example 4:
Input: A = “aaaaaaabc”, B = “aaaaaaacb”
Output: true
Example 5:
Input: A = “”, B = “aa”
Output: false
Note:
0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist only of lowercase letters.
class Solution(object):
def buddyStrings(self, A, B):
if len(A) != len(B): #长度不同必然不行,如"aa"和""
return False
if A==B and len(A)>len(set(A)): #如果A和B相同,则要判断A(B)中存不存在重复元素,set()可以帮助我们去除重复元素,如果存在重复元素则可判断True。 如:"abc"和“abc”是不行的(不存在重复元素,怎么换也没用),但是"abab"和“abab”就是True;再比如“aa”和"aa"可以,但是"ab"和“ab”就不行。
return True
tempA=[] #如果A和B不是完全相同的,则我们要判断交换一次能不能使A和B相同
tempB=[] # tempA和tempB用来依次保存A,B中不同的值
for i in range(len(A)):
if A[i]!=B[i]: #寻找A,B中不同的值
tempA.append(A[i]) #添加到列表中
tempB.append(B[i])
if len(tempA)>2: #易知,只能交换一次意味着A和B中只能存2对不同值。比如:"abcd"和"bacd",在tempA中存[a,b], 在tempB中存[b,a],这两对不同值交换后就能实现A,B相同;但是“abcd”和"badc",在tempA中存[a,b,c,d], 在tempB中存[b,a,d,c],显然只一次交换不行,所以很容易明白len(tempA)不能大于2
return False
if len(tempA)==2 and tempA==tempB[::-1]: #当len(tempA)等于2时也要注意,此时只是交换可能成功,还要判断一下,比如“ab”和“ba”交换肯定可以成功,但是"ab"和“ca”显然不行。判断的方法就是tempA中存的元素顺序要等于tempB中存的元素的逆序,如“ab”和“ba”
return True