LeetCode 859 Buddy Strings
题目分析
Given two strings
A
andB
of lowercase letters, returntrue
if and only if we can swap two letters inA
so that the result equalsB
.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.
给定2个字符串,判断是否是兄弟字符串,兄弟字符串的定义就是交换某个字符串中的2个字符可以和另一个字符串相同,这两个字符串就是兄弟字符串。
思考
字符串互为兄弟字符串要求交换自己的某两个字符串可以和另一个相等,首先判断长度是否相等,然后同时遍历两个字符串找到所有的不同字符的下标,记录下标数目。如果下标数目为0的话判断说明两个字符串相等,但是根据题目要求必须交换两个不同下标字符后相等才是兄弟字符串,这样的话直接检测字符串中是否有重复字符串就可以了,不存在的局部是兄弟字符串,然后判断下标数目是否是2,不是2返回false
,交换不同的两个字符,返回是否相等就可以了。
代码实现
class Solution {
public:
bool buddyStrings(string A, string B) {
if (A.length() != B.length()) {
return false;
}
// 交换两个字符使得AB相同
// 检测A和B中不同的字符位置个数
int diff_cnt = 0;
int idxs[20005] = { 0, 0 };
for (int i = 0; i < A.length(); ++i) {
if (A[i] != B[i]) {
idxs[diff_cnt++] = i;
}
}
if (diff_cnt == 0) {
// 没有不同
// 看A里是否有相同的字符串
map<char, bool> m;
for (auto &ch : A) {
if (m[ch]) {
return true;
}
else {
m[ch] = true;
}
}
return false;
}
if (diff_cnt != 2) {
return false;
}
swap(A[idxs[0]], A[idxs[1]]);
return A == B;
}
};
感想
略