forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuddy Strings.java
More file actions
36 lines (36 loc) · 907 Bytes
/
Buddy Strings.java
File metadata and controls
36 lines (36 loc) · 907 Bytes
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
class Solution {
public boolean buddyStrings(String s, String goal) {
if (s.length() != goal.length()) {
return false;
}
if (s.equals(goal)) {
Set<Character> set = new HashSet<>();
for (char c : s.toCharArray()) {
if (set.contains(c)) {
return true;
}
set.add(c);
}
return false;
}
char[] mismatch = {'-', '-'};
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
if (mismatch[0] == '|') {
return false;
}
if (mismatch[0] == '-') {
mismatch[0] = s.charAt(i);
mismatch[1] = goal.charAt(i);
} else {
if (goal.charAt(i) == mismatch[0] && s.charAt(i) == mismatch[1]) {
mismatch[0] = '|';
continue;
}
return false;
}
}
}
return mismatch[0] == '|';
}
}