859. Buddy Strings

Easy

273160FavoriteShare

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


注意:如果A和B不一样的地方不是2处,那么肯定返回false。如果A和B是一样的,那么久判断A是否有两个一样的字母,因为这两个一样的字母swap后得到的字符串与swap前得到的是一样的。如果A和B不一样的地方是2处,那么记录一下这2处的下标,swap一下,看一看swap前后是否一致。具体思路就是这样。时间复杂度为O(n),空间复杂度为O(n)

class Solution {
public:
bool buddyStrings(string A, string B) {
int Index[20005] = { 0,0 };
int Different_Num = 0;
for (int i = 0; i < A.size(); i++) {
if (A[i] != B[i])
{
Index[Different_Num++] = i;
}
}
//A和B一样
if (Different_Num == 0) {
unordered_map<int, bool> HashMap;
for (auto a : A) {
if (HashMap[a]) {
return true;
}
else {
HashMap[a] = true;
}
}
return false;
}
//A和B有2个地方不一样
else if (Different_Num == 2) {
swap(B[Index[0]], B[Index[1]]);
return A == B;
}
else {
return false;
}
}
};