Minimum Swaps to Make Strings Equal
Difficulty: Easy
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.
Example 1:
Input: s1 = “xx”, s2 = “yy”
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = “yx”, s2 = “yx”.
Example 2:
Input: s1 = “xy”, s2 = “yx”
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = “yy”, s2 = “xx”.
Swap s1[0] and s2[1], s1 = “xy”, s2 = “xy”.
Note that you can’t swap s1[0] and s1[1] to make s1 equal to “yx”, cause we can only swap chars in different strings.
Example 3:
Input: s1 = “xx”, s2 = “xy”
Output: -1
Example 4:
Input: s1 = “xxyyxyxyxx”, s2 = “xyyxyxxxyx”
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain ‘x’ or ‘y’.
题意
给定两个字符串s1
, s2
,s1
, s2
均只包含x
和y
,定义一次swap
操作为交换s1[i]
和s2[j]
,求最少多少次swap
,可以使得s1 == s2
.
代码
注意到以下三个事实:
s1
和s2
中x
的个数之和和y
的个数之和必须是偶数xx - yy
需要1次swap
xy - yx
需要2次swap
因此,算法计算x - y
和y - x
的个数xy
和yx
,首先排除不满足事实1的情况,返回-1,然后优先利用事实2削减xy
和yx
,剩下的用事实2,直到xy = yx = 0
.
代码
class Solution {
public int minimumSwap(String s1, String s2) {
int n = s1.length(), i = 0, xy = 0, yx = 0;
for (i=0; i<n; ++i) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 == 'x' && c2 == 'y') {
++xy;
}
if (c1 == 'y' && c2 == 'x') {
++yx;
}
}
if ((xy - yx) % 2 != 0) {
return -1;
}
if (xy == 0 && yx == 0) {
return 0;
}
if (xy % 2 == 0 && yx % 2 == 0) {
return xy / 2 + yx / 2;
}
return Math.min(xy, yx) + 1 + Math.abs(xy - yx) / 2;
}
}