Skip to content

Commit d9a05d9

Browse files
authored
Update Check if One String Swap Can Make Strings Equal.java
1 parent c259c7a commit d9a05d9

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed
Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
class Solution {
2-
public boolean areAlmostEqual(String s1, String s2) {
3-
int mismatchIdx = -1;
4-
for (int i = 0; i < s1.length(); i++) {
5-
if (s1.charAt(i) != s2.charAt(i)) {
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));
2+
public boolean areAlmostEqual(String s1, String s2) {
3+
int swapIdx = -1;
4+
boolean swapped = false;
5+
for (int i = 0; i < s1.length(); i++) {
6+
if (s1.charAt(i) != s2.charAt(i)) {
7+
if (swapped) {
8+
return false;
9+
}
10+
if (swapIdx != -1) {
11+
if (!(s1.charAt(swapIdx) == s2.charAt(i) && s1.charAt(i) == s2.charAt(swapIdx))) {
12+
return false;
13+
}
14+
swapped = true;
15+
}
16+
swapIdx = i;
17+
}
1018
}
11-
mismatchIdx = i;
12-
}
19+
return swapIdx == -1 || (swapIdx != -1 && swapped);
1320
}
14-
return mismatchIdx == -1;
15-
}
1621
}

0 commit comments

Comments
 (0)