File tree 1 file changed +17
-12
lines changed
1 file changed +17
-12
lines changed Original file line number Diff line number Diff line change 1
1
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
+ }
10
18
}
11
- mismatchIdx = i ;
12
- }
19
+ return swapIdx == -1 || (swapIdx != -1 && swapped );
13
20
}
14
- return mismatchIdx == -1 ;
15
- }
16
21
}
You can’t perform that action at this time.
0 commit comments