-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBuddyString.java
64 lines (56 loc) · 2.24 KB
/
BuddyString.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package leetcode.string;
import java.util.HashSet;
import java.util.Set;
public class BuddyString {
public boolean buddyStrings(String A, String B) {
// Returns false directly if two strings are not the same length.
if (A.length() != B.length()) {
return false;
}
// To store the index of the first different pair of characters.
int firstDiff = -1;
// To store the index of the second different pair of characters.
int secondDiff = -1;
// Uses this to check whether there exists duplicate characters in string A.
Set<Character> chars = new HashSet<>();
boolean hasDuplicate = false;
char currentA;
char currentB;
// Iterates through each character for string A and B.
for (int i = 0; i < A.length(); i++) {
currentA = A.charAt(i);
currentB = B.charAt(i);
if (currentA != currentB) {
if (firstDiff == -1) {
// Records the position of the first different pair.
firstDiff = i;
} else if (secondDiff != -1) {
// Returns false if there are more than two different pairs.
return false;
} else if (A.charAt(firstDiff) == currentB && currentA == B.charAt(firstDiff)) {
// Records the position of the second different pair.
secondDiff = i;
} else {
// Returns false if two strings are not the same after swap.
return false;
}
}
if (!hasDuplicate) {
if (chars.contains(currentA)) {
hasDuplicate = true;
} else {
chars.add(currentA);
}
}
}
// Returns true only if they could be possibly the same after exactly one swap.
if (firstDiff != -1 && secondDiff != -1) {
return true;
} else if (firstDiff == -1 && secondDiff == -1) {
// Special case when the two strings are the same (they may have duplicate characters).
return hasDuplicate;
} else {
return false;
}
}
}