LeetCode 859.亲密字符串
找到AB 两个字符串不相同的第一个位置和第二个位置
A[i] = B[j] 且 A[j] = B[i] ,剩余的字符串应当相同
特殊情况:如果AB字符串相等,判断A中有重复的字符则正确
class Solution {
public:
bool has_repeate(string a){
int cnt[26] = {0};
for(int i = 0; a[i]; i++){
cnt[a[i] - 'a'] += 1;
if(cnt[a[i] - 'a'] == 2) return true;
}
return false;
}
bool buddyStrings(string a, string b) {
if(a.size() != b.size()) return false;
if(a == b ) return has_repeate(a);
int i = 0, j;
while(a[i] == b[i]) ++i;
j = i + 1;
while(j < a.size() && a[j] == b[j]) ++j;
if(j == a.size()) return false;
if(a[i] != b[j] || a[j] != b[i]) return false;
j += 1;
while(j < a.size()){
if(a[j] != b[j]) return false;
j += 1;
}
return true;
}
};