题目:
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
andB
consist only of lowercase letters.
解释:
如果A和B长度不相等,一定是false
如果A和B相等,那么A中一定要有重复元素,而且交换的时候交换重复元素才能true。
如果A和B仅仅是长度相等而本身不相等,那么顺序遍历,若A[i]和B[i]不相等,则记录这对,最后不相等的一定要是两对,而且这两对互为相反。
python代码:
class Solution(object):
def buddyStrings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A)!=len(B):
return False
if A==B and len(A)!=len(set(A)):
return True
dif=[(a,b) for a,b in zip(A,B) if a!=b]
return len(dif)==2 and dif[0]==dif[1][::-1]
c++代码:
class Solution {
public:
bool buddyStrings(string A, string B) {
int len_A=A.size(),len_B=B.size();
set<int>set_A(A.begin(),A.end());
if(len_A!=len_B)
return false;
if(A==B && len_A!=set_A.size())
return true;
vector<vector<char>>dif;
for(int i=0;i<len_A;i++)
{
if (A[i]!=B[i])
{
dif.push_back({A[i],B[i]});
}
}
if (dif.size()!=2)
return false;
vector<char> dif1=dif[1];
reverse(dif1.begin(),dif1.end());
return dif[0]==dif1;
}
};
总结: