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
44 lines (44 loc) · 1.16 KB
/
Buddy Strings.java
File metadata and controls
44 lines (44 loc) · 1.16 KB
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
class Solution {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length()) {
return false;
}
char requiredChar = '-';
char mismatchChar = '-';
int[] counter = new int[26];
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) != B.charAt(i)) {
// Already done one swap hence cannot do any more swaps
if (requiredChar == '_') {
return false;
}
if (requiredChar == '-') {
requiredChar = B.charAt(i);
mismatchChar = A.charAt(i);
}
else {
// Check if swap is possible from previous mismatch
if (B.charAt(i) == mismatchChar && A.charAt(i) == requiredChar) {
requiredChar = '_';
}
else {
return false;
}
}
}
else {
counter[A.charAt(i) - 'a']++;
}
}
if (mismatchChar != '-') {
return requiredChar == '_';
}
// Check if we have more than 1 occurrence of same characters. We can swap them to fulfil the condition
for (int i = 0; i < 26; i++) {
if (counter[i] > 1) {
return true;
}
}
return false;
}
}