class Solution {
public:
bool buddyStrings(string A, string B) {
int length1 = A.length();
int length2 = B.length();
bool s[26]={false};
if(length1!=length2)return false;
int start=0,last = 0;
// repeat 当A=B时,A中是否有字母出现了两次。
//find 用来标识是否已经找到了一次交换可以使A和B的前半部分相同
bool first=true,repeat=false,find =false;
for(int i=0;i<length1;i++)
{
if(s[A[i]-'a']==false)s[A[i]-'a']=true;
else repeat = true;
if(A[i]==B[i])continue;
else if(find)return false;
else if(first)
{
start = i;
first = false;
}
else
{
last = i;
if(A[start]==B[last]&&A[last]==B[start])
{
find=true;
}
else return false;
}
}
if(repeat)return true;
else if(find) return true;
else return false;
}
};