描述
这道题交换两个字符后相等
我的做法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59class Solution {
public:
bool buddyStrings(string A, string B) {
if (A.length() != B.length())//长度不同直接返回false
{
return false;
}
int strLength = A.length();
if (A==B)//字符串一样直接返回true
{
//存在两个相同的字符才可以
for (int i = 0; i < strLength; i++)
{
for (int j = i + 1; j < strLength; j++)
{
if (A.at(i) == A.at(j))
{
return true;
}
}
}
return false;
}
int ind1, ind2;//能成功的必须只有两处不同
int flag = 0;
for (int i = 0; i < strLength; i++)
{
if (A.at(i) != B.at(i))
{
flag++;
if (flag == 1)
{
ind1 = i;
}
else if (flag == 2)
{
ind2 = i;
}
else
{
return false;
}
}
}
int temp_val = A.at(ind1);
A.at(ind1) = A.at(ind2);
A.at(ind2) = temp_val;
if (A == B)
{
return true;
}
else
{
return false;
}
}
};
大佬做法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30class Solution {
public:
bool buddyStrings(string A, string B) {
if (A.length() != B.length()) {
return false;
}
if (A.length() < 2) {
return false;
}
bool bRpeat = false;
bool map[26] = {false};
int diffCnt = 0;
int ind[2];
for (int i = 0; i < A.length(); i++)
{
if (map[A[i] - 'a']) { bRpeat = true; }
map[A[i] - 'a'] = true;
if (A[i] != B[i]) {
if (diffCnt >= 2) { return false; }
ind[diffCnt++] = i;
}
}
if (diffCnt == 0 && bRpeat) { return true; }
return A[ind[0]] == B[ind[1]] && A[ind[1]] == B[ind[0]];
}
};
**参考资料*
[原题链接](https://leetcode.com/problems/buddy-strings/description/)