859.Buddy Strings
859.Buddy Strings
难度:Easy
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.
1
Example 1:
2
3
Input: A = "ab", B = "ba"
4
Output: true
5
Example 2:
6
7
Input: A = "ab", B = "ab"
8
Output: false
9
Example 3:
10
11
Input: A = "aa", B = "aa"
12
Output: true
13
Example 4:
14
15
Input: A = "aaaaaaabc", B = "aaaaaaacb"
16
Output: true
17
Example 5:
18
19
Input: A = "", B = "aa"
20
Output: false
21
22
23
Note:
24
25
0 <= A.length <= 20000
26
0 <= B.length <= 20000
27
A and B consist only of lowercase letters.
Copied!
判断两个字串是否相等,如果相等,看看有没有重复的字母,有则可以交换,没有则返回false。 两个字串不相等,则比较不相等的位置,是不是刚好有两个,并判断两个是不是交换之后相等。
1
class Solution {
2
public:
3
bool buddyStrings(string A, string B) {
4
if(A.length() != B.length() ) return false;
5
if(A==B)
6
{
7
vector<int>alpha(26,0);
8
for(auto c:A)
9
{
10
if(++alpha[c-'a'] >1) return true;
11
}
12
return false;
13
}
14
int count=0;
15
vector<int> index;
16
for(int i=0;i<A.length();i++)
17
{
18
if(A[i] !=B[i])
19
{
20
count++;
21
index.push_back(i);
22
}
23
}
24
if(count !=2) return false;
25
//cout<< index[0] <<" "<<index[1]<<endl;
26
if(A[index[0]] == B[index[1]] && A[index[1]] == B[index[0]]) return true;
27
return false;
28
}
29
};
Copied!
执行用时 :8 ms, 在所有 C++ 提交中击败了81.11%的用户 内存消耗 :9.1 MB, 在所有 C++ 提交中击败了49.58%的用户
Copy link