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:
1
2
Input: A = "ab", B = "ba"
Output: true
  • Example 2:

    1
    2
    Input: A = "ab", B = "ab"
    Output: false
  • Example 3:

    1
    2
    Input: A = "aa", B = "aa"
    Output: true
  • Example 4:

1
2
Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
  • Example 5:
1
2
Input: A = "", B = "aa"
Output: false

Note:

  1. 0 <= A.length <= 20000
  2. 0 <= B.length <= 20000
  3. A and B consist only of lowercase letters.

交换A字符串的两个字符,使得 A = B.

实现

  • java
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
public boolean (String A, String B) {

if (A.length() != B.length() ) {
return false;
}
if (A.length() < 2 || B.length() < 2){
return false;
}
int len = A.length();
char[] chA = A.toCharArray();
char[] chB = B.toCharArray();
int modCount = 0;
char[] ele = new char[4];
Set<Character> keySet = new HashSet<>();
for (int i = 0; i < len; i++) {
char a = chA[i];
char b = chB[i];
keySet.add(a);
if (modCount > 2){
return false;
}
if (a != b) {
modCount += 1;
if (ele[0] == 'u0000'){
ele[0] = a;
ele[1] = b;
} else {
ele[2] = a;
ele[3] = b;
}
}
}
if (modCount == 0){
return keySet.size() < chA.length;
}
return ele[0] == ele[3] && ele[1] == ele[2];
}

讨论区其他答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public boolean (String A, String B) {
if (A.length() != B.length()){
return false;
}

if (A.equals(B)) {
Set<Character> s = new HashSet<Character>();
for (char c : A.toCharArray()) {
s.add(c);
}
return s.size() < A.length();
}
List<Integer> dif = new ArrayList<>();
for (int i = 0; i < A.length(); ++i) if (A.charAt(i) != B.charAt(i)) dif.add(i);
return dif.size() == 2 && A.charAt(dif.get(0)) == B.charAt(dif.get(1)) && A.charAt(dif.get(1)) == B.charAt(dif.get(0));
}

参考资料