1 class Solution:
 2     def minimumSwap(self, s1: str, s2: str) -> int:
 3         type1,type2 = 0,0
 4         n = len(s1)
 5         for i in range(n):
 6             if s1[i] == 'x' and s2[i] == 'y':
 7                 type1 += 1
 8             elif s1[i] == 'y' and s2[i] == 'x':
 9                 type2 += 1
10         d1,r1 = type1 // 2,type1 % 2
11         d2,r2 = type2 // 2,type2 % 2
12         if r1 + r2 == 1:
13             return -1
14         else:
15             return d1 + d2 + r1 + r2

这是一道数学计算题目,将s1和s2按字符进行判断,分三种情况讨论:

s1是x,s2是y的情况,记录为数量type1

s1是y,s2是x的情况,记录为数量type2

s1与s2同是x或同是y的情况,忽略,不用处理

对于type1,可以进行(type1 // 2) * 1 次交换,使对应位置都变为一样的字符,对应"xx"与"yy"形式。

对于type2,可以进行(type2 // 2) * 1次交换,使对应位置都变为一样的字符,对应"yy"与"xx"形式。

那剩下的两个余数type1 % 2与type2 % 2,如果一个是1,一个是0,那么说明最后无法交换(x和y的数量不匹配),返回-1。

否则,两个都是0,无需再进行交换;两个都是1,则再进行2次交换,对应"xy"与"yx"形式。

posted on 2019-11-03 16:04  Sempron2800+  阅读(271)  评论(0编辑  收藏  举报