Skip to content

Commit 651cb02

Browse files
refactor 859
1 parent bf0695d commit 651cb02

File tree

1 file changed

+28
-63
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+28
-63
lines changed

src/main/java/com/fishercoder/solutions/_859.java

+28-63
Original file line numberDiff line numberDiff line change
@@ -3,70 +3,35 @@
33
import java.util.HashSet;
44
import java.util.Set;
55

6-
/**
7-
* 859. Buddy Strings
8-
*
9-
* 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.
10-
*
11-
*
12-
*
13-
* Example 1:
14-
*
15-
* Input: A = "ab", B = "ba"
16-
* Output: true
17-
* Example 2:
18-
*
19-
* Input: A = "ab", B = "ab"
20-
* Output: false
21-
* Example 3:
22-
*
23-
* Input: A = "aa", B = "aa"
24-
* Output: true
25-
* Example 4:
26-
*
27-
* Input: A = "aaaaaaabc", B = "aaaaaaacb"
28-
* Output: true
29-
* Example 5:
30-
*
31-
* Input: A = "", B = "aa"
32-
* Output: false
33-
*
34-
*
35-
* Note:
36-
*
37-
* 0 <= A.length <= 20000
38-
* 0 <= B.length <= 20000
39-
* A and B consist only of lowercase letters.
40-
*/
416
public class _859 {
42-
public static class Solution1 {
43-
public boolean buddyStrings(String A, String B) {
44-
if (A.length() != B.length()) {
45-
return false;
46-
}
47-
Character c1 = null;
48-
Character c2 = null;
49-
Set<Character> set = new HashSet<>();
50-
int count = 0;
51-
for (int i = 0; i < A.length(); i++) {
52-
if (A.charAt(i) != B.charAt(i)) {
53-
if (count > 2) {
54-
return false;
55-
}
56-
if (c1 == null) {
57-
c1 = B.charAt(i);
58-
c2 = A.charAt(i);
59-
count++;
60-
continue;
61-
}
62-
if (c1 != A.charAt(i) || c2 != B.charAt(i)) {
63-
return false;
64-
}
65-
count++;
7+
public static class Solution1 {
8+
public boolean buddyStrings(String A, String B) {
9+
if (A.length() != B.length()) {
10+
return false;
11+
}
12+
Character c1 = null;
13+
Character c2 = null;
14+
Set<Character> set = new HashSet<>();
15+
int count = 0;
16+
for (int i = 0; i < A.length(); i++) {
17+
if (A.charAt(i) != B.charAt(i)) {
18+
if (count > 2) {
19+
return false;
20+
}
21+
if (c1 == null) {
22+
c1 = B.charAt(i);
23+
c2 = A.charAt(i);
24+
count++;
25+
continue;
26+
}
27+
if (c1 != A.charAt(i) || c2 != B.charAt(i)) {
28+
return false;
29+
}
30+
count++;
31+
}
32+
set.add(A.charAt(i));
33+
}
34+
return count == 2 || (count == 0 && set.size() < A.length());
6635
}
67-
set.add(A.charAt(i));
68-
}
69-
return count == 2 || (count == 0 && set.size() < A.length());
7036
}
71-
}
7237
}

0 commit comments

Comments
 (0)