难度: Easy
原题连接
内容描述
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.
思路 1 - 时间复杂度: O(N^2)- 空间复杂度: O(1)******
- 如果A和B长度都不同肯定不行
- 如果A和B完全相同那么就要看A中是否有两个相同的字母,因为这样一交换A没有变化所以就是B了
- 如果A和B不同的字母数是2的话,就看看是否可以换一下变成一样
- 其他都返回False
beats 99.38%
class Solution:
def buddyStrings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A) != len(B):
return False
diff = []
for i in range(len(A)):
if A[i] != B[i]:
diff.append(A[i]+B[i])
if len(diff) == 2:
if diff[1][::-1] == diff[0]:
return True
else:
return False
elif len(diff) == 0:
return any(i > 1 for i in collections.Counter(A).values())
else:
return False