Skip to content

Commit 3c00860

Browse files
authored
Added Check if One String Swap Can Make Strings Equal.java
1 parent eb2a473 commit 3c00860

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public final int UNSET_INDEX = -1;
3+
public final int SET_INDEX = 101;
4+
public boolean areAlmostEqual(String s1, String s2) {
5+
int swapIndex = UNSET_INDEX;
6+
for (int i = 0; i < s1.length(); i++) {
7+
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;
17+
}
18+
}
19+
}
20+
return swapIndex == UNSET_INDEX || swapIndex == SET_INDEX;
21+
}
22+
}

0 commit comments

Comments
 (0)