1247. Minimum Swaps to Make Strings Equal
- Minimum Swaps to Make Strings Equal python solution
题目描述
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.
解析
将s1和s2对应成字符对
Example 1:
s1 = “xx”
s2 = “yy”
在0和1两个索引位置,字符对均为x_y,只需要交换一次,使s1和s2相等
Example 2:
s1 = “yy”
s2 = “xx”
在0和1两个索引位置,字符对均为y_x,只需要交换一次,使s1和s2相等
Example 3:
s1 = “xy”
s2 = “yx”
在0这个索引位置,字符对为x_y。在1这个索引位置,字符对为y_x。所以需要交换两次,使s1和s2相等。
Example 4:
s1 = “xxyyxyxyxx”,
s2 = “xyyxyxxxyx”
首先移除掉在同一索引位置相同的元素,得到
s1 = “xyxyyx”
s2 = “yxyxxy”
则
“x_y” count = 3 (index 0, 2, 5)
“y_x” count = 3 (index 1, 3, 4)
如例子1,索引位置0和2只需要一次交换。如例子2,索引位置1和3需要一次交换。如例子3,索引位置5和4需要两次交换。所以一共需要四次交换。
故解题步骤如下:
计算字符对"x_y" and "y_x"的个数
如果两者的总和为奇数,直接返回-1,因为s1字符串和s2字符串中x,y的个数不相等
每两个x_y需要一次交换,每两个y_x需要一次交换
如果最后剩下一个x_y和y_x,那么再需要两次交换。
// An highlighted block
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
x_y,y_x=0,0
res=0
for c1, c2 in zip(s1,s2):
if c1!=c2:
if c1=='x':
x_y+=1
else:y_x+=1
if (x_y+y_x)%2==1:
return -1
res+=x_y//2
res+=y_x//2
if x_y%2==1:
res+=2
return res
Reference
https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/discuss/419874/Simply-Simple-Python-Solution-with-detailed-explanation