题意:给定两个字符串 字符串之间可以单次交换一个字符
但是字符串内部不能够交换
最终使得上下两个字符串相同
思路:判断总体x,y数量的奇偶,若为奇数则必不能满足,偶数则必须满足 若上下字符串两个为x-y x-y 则只需要交换一次变为x-x y-y,y-x y-x同类,但是xx yy由于同组不能交换 则需要交换两次。
code:
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
num1x = s1.count('x')
num1y = s1.count('y')
num2x = s2.count('x')
num2y = s2.count('y')
if (num1x + num2x) % 2 == 1 or (num1y + num2y) == 1:
return -1
else:
ans1 = 0
ans2 = 0
for i in range(len(s1)):
if s1[i] == 'x' and s2[i] == 'y':
ans1 += 1
elif s1[i] == 'y' and s2[i] == 'x':
ans2 += 1
ans = ans1 // 2 + ans2 // 2
if ans1 % 2 == 1 or ans2 % 2 == 1:
ans += 2
return ans