[LeetCode] Minimum Swaps to Make Strings Equal

1247. Minimum Swaps to Make Strings Equal

You are given two strings s1 and s2 of equal length consisting of letters “x” and “y” only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].

Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int minimumSwap(string A, string B) {
int xy = 0, yx = 0, n = A.length();
for(int i = 0; i < n; i++) {
if(A[i] == 'x' and B[i] == 'y') xy++;
else if(A[i] == 'y' and B[i] == 'x') yx++;
}
if(xy % 2 != yx % 2) return -1;
return xy / 2 + yx / 2 + (xy & 1) * 2;

}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/18/PS/LeetCode/minimum-swaps-to-make-strings-equal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.