Skip to content

Commit ff72fce

Browse files
authored
Create 1247-minimum-swaps-to-make-strings-equal.js
1 parent 5912ca5 commit ff72fce

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {string} s1
3+
* @param {string} s2
4+
* @return {number}
5+
*/
6+
const minimumSwap = function (s1, s2) {
7+
let x1 = 0 // number of 'x' in s1 (skip equal chars at same index)
8+
let y1 = 0 // number of 'y' in s1 (skip equal chars at same index)
9+
let x2 = 0 // number of 'x' in s2 (skip equal chars at same index)
10+
let y2 = 0 // number of 'y' in s2 (skip equal chars at same index)
11+
12+
for (let i = 0; i < s1.length; i++) {
13+
let c1 = s1.charAt(i)
14+
let c2 = s2.charAt(i)
15+
if (c1 == c2) {
16+
// skip chars that are equal at the same index in s1 and s2
17+
continue
18+
}
19+
if (c1 == 'x') {
20+
x1++
21+
} else {
22+
y1++
23+
}
24+
if (c2 == 'x') {
25+
x2++
26+
} else {
27+
y2++
28+
}
29+
} // end for
30+
31+
// After skip "c1 == c2", check the number of 'x' and 'y' left in s1 and s2.
32+
if ((x1 + x2) % 2 != 0 || (y1 + y2) % 2 != 0) {
33+
return -1 // if number of 'x' or 'y' is odd, we can not make s1 equals to s2
34+
}
35+
36+
let swaps = Math.floor(x1 / 2) + Math.floor(y1 / 2) + (x1 % 2) * 2
37+
// Cases to do 1 swap:
38+
// "xx" => x1 / 2 => how many pairs of 'x' we have ?
39+
// "yy" => y1 / 2 => how many pairs of 'y' we have ?
40+
//
41+
// Cases to do 2 swaps:
42+
// "xy" or "yx" => x1 % 2
43+
44+
return swaps
45+
}

0 commit comments

Comments
 (0)