File tree 1 file changed +17
-10
lines changed
scripts/algorithms/M/Minimum Swaps to Make Strings Equal
1 file changed +17
-10
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 0 ms (Top 100.0%) | Memory: 41.80 MB (Top 5.91%)
2
+
1
3
class Solution {
2
4
public int minimumSwap (String s1 , String s2 ) {
3
- if (s1 .length () != s2 .length ()) return -1 ;
4
- int n = s1 .length ();
5
- int x = 0 , y = 0 ;
6
5
7
- for (int i = 0 ; i < n ; i ++){
8
- char c1 = s1 .charAt (i ) , c2 = s2 .charAt (i );
9
- if (c1 == 'x' && c2 == 'y' ) x ++;
10
- else if (c1 == 'y' && c2 == 'x' ) y ++;
6
+ int count = 0 ;
7
+ int cnt_1 = 0 ;
8
+ int cnt_2 = 0 ;
9
+ char [] a = s1 .toCharArray ();
10
+ char [] b = s2 .toCharArray ();
11
+
12
+ for (int i =0 ;i <a .length ;i ++){
13
+ if (a [i ] != b [i ]){
14
+ count ++;
15
+ if (a [i ] == 'x' ) cnt_1 ++;
16
+ else cnt_2 ++;
17
+ }
11
18
}
12
19
13
- if (x % 2 == 0 && y % 2 == 0 ) return x / 2 + y / 2 ;
14
- else if ( x % 2 == 1 && y % 2 == 1 ) return x / 2 + y / 2 + 2 ;
15
- return - 1 ;
20
+ if (count % 2 == 1 )
21
+ return - 1 ;
22
+ else return cnt_1 / 2 + cnt_2 / 2 +( cnt_1 % 2 )* 2 ;
16
23
}
17
24
}
You can’t perform that action at this time.
0 commit comments