版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hh66__66hh/article/details/82729250
#LeetCode #859. Buddy Strings
##题目描述
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
##解题思路
分以下情况分析:
(1)看A和B长度是否相等,如果不相等则返回false;
(2)A和B长度相等,看A是否和B完全一样:
1)A和B完全一样,则看A(B)中是否有相同的字符,如果有则返回true,没有则返回false;
2)A和B不一样,则看有几位不一样,如果有超过2位不一样,或者只有1位不一样,则返回false;否则看不一样的那两位,调换后是否就一样了。
##代码
class Solution {
public:
bool buddyStrings(string A, string B) {
if(A.length() != B.length()) {
return false;
}
int i, j, k, ans, l, r;
map<char,int>m;
m.clear();
if(A == B) {
for(i=0; i<A.length(); i++) {
if(m.count(A[i])>0) {
return true;
}
m[A[i]] = 1;
}
return false;
}
ans = 0;
for(i=0; i<A.length(); i++) {
if(A[i] != B[i]) {
if(ans>2) {
return false;
}
ans++;
if(ans==1) {
l = i;
}
else if(ans==2) {
r = i;
}
}
}
if(A[l]==B[r] && A[r]==B[l]) {
return true;
}
return false;
}
};