题目:
给定两个由小写字母构成的字符串 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
AC代码:
class Solution {
public:
bool buddyStrings(string A, string B) {
if(A.length() != B.length())
return false;
if(A.length() == 0 && B.length() == 0){
return false;
}
int count = 0;
int x[2] = {0};
int vocabulary[28] = {0};
char p = A[0];
int check = 0;
int check2 = 0;
for(int i=0;i!=A.length();++i){
if(++vocabulary[A[i]-97] >= 2)
check2 = 1;
if(i!=A.length()-1 && A[i] != A[i+1]){
check = 1;
}
if(A[i] != B[i]){
if(++count > 2){
return false;
}
x[count - 1] = i;
}
}
if(count == 2 && A[x[1]] == B[x[0]] && B[x[1]] == A[x[0]]){
return true;
}
if((count == 0 && check == 0) ||
(count == 0 && check2 == 1))
return true;
return false;
}
};