題意:給定兩個字符串 字符串之間可以單次交換一個字符
但是字符串內部不能夠交換
最終使得上下兩個字符串相同
思路:判斷總體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