forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_859.java
37 lines (35 loc) · 1.13 KB
/
_859.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
package com.fishercoder.solutions;
import java.util.HashSet;
import java.util.Set;
public class _859 {
public static class Solution1 {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length()) {
return false;
}
Character c1 = null;
Character c2 = null;
Set<Character> set = new HashSet<>();
int count = 0;
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) != B.charAt(i)) {
if (count > 2) {
return false;
}
if (c1 == null) {
c1 = B.charAt(i);
c2 = A.charAt(i);
count++;
continue;
}
if (c1 != A.charAt(i) || c2 != B.charAt(i)) {
return false;
}
count++;
}
set.add(A.charAt(i));
}
return count == 2 || (count == 0 && set.size() < A.length());
}
}
}