Skip to content

Commit 0694719

Browse files
authored
Update Check if One String Swap Can Make Strings Equal.java
1 parent 32d86ff commit 0694719

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed
Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,16 @@
11
class Solution {
2-
public final int UNSET_INDEX = -1;
3-
public final int SET_INDEX = 101;
42
public boolean areAlmostEqual(String s1, String s2) {
5-
int swapIndex = UNSET_INDEX;
3+
int mismatchIdx = -1;
64
for (int i = 0; i < s1.length(); i++) {
75
if (s1.charAt(i) != s2.charAt(i)) {
8-
if (swapIndex == SET_INDEX) {
9-
return false;
10-
} else if (swapIndex == UNSET_INDEX) {
11-
swapIndex = i;
12-
} else {
13-
if (!(s1.charAt(swapIndex) == s2.charAt(i) && s1.charAt(i) == s2.charAt(swapIndex))) {
14-
return false;
15-
}
16-
swapIndex = SET_INDEX;
6+
if (mismatchIdx != -1) {
7+
return s1.charAt(mismatchIdx) == s2.charAt(i) &&
8+
s1.charAt(i) == s2.charAt(mismatchIdx) &&
9+
s1.substring(i + 1).equals(s2.substring(i + 1));
1710
}
11+
mismatchIdx = i;
1812
}
1913
}
20-
return swapIndex == UNSET_INDEX || swapIndex == SET_INDEX;
14+
return mismatchIdx == -1;
2115
}
2216
}

0 commit comments

Comments
 (0)