Buddy Strings LeetCode solution in Java

1
class Solution {
2
public boolean buddyStrings(String s, String goal) {
3
char a = '\u0000', b = '\u0000';
4
char c = '\u0000', d = '\u0000';
5
int lenS = s.length();
6
int lenGoal = goal.length();
7
boolean flag = true;
8
HashSet<Character> hset = new HashSet<>();
9

10
if (lenS != lenGoal) return false;
11

12
if (s.equals(goal)) {
13
for (int i = 0; i < lenS; i++) {
14
if (!hset.contains(s.charAt(i))) {
15
hset.add(s.charAt(i));
16
} else return true;
17
}
18
return false;
19
} else {
20
for (int i = 0; i < lenS; i++) {
21
if (s.charAt(i) == goal.charAt(i)) {
22
continue;
23
}
24
if (a == '\u0000') {
25
a = s.charAt(i);
26
c = goal.charAt(i);
27
continue;
28
}
29
if (b == '\u0000') {
30
b = s.charAt(i);
31
d = goal.charAt(i);
32
continue;
33
}
34
return false;
35
}
36

37
if (a == d && c == b && a != '\u0000') return true;
38

39
return false;
40
}
41
}
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0