[leetcode] 1247. Minimum Swaps to Make Strings Equal

网友投稿 801 2022-08-23

[leetcode] 1247. Minimum Swaps to Make Strings Equal

[leetcode] 1247. Minimum Swaps to Make Strings Equal

Description

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: 1Explanation: Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".

Example 2:

Input: s1 = "xy", s2 = "yx"Output: 2Explanation: 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 <= 1000s1, s2 only contain ‘x’ or ‘y’.

分析

题目的意思是:给定两个字符串,用最小的交换步骤是的两个字符串相等。这道题我觉得挺难的,第一,相同位置相等的字符不影响最小交换步骤的求解;另外,除此之外,最小交换步骤res=x_y/2+y_x/2 其中x_y为字符串1中不等于字符串2的x的个数,y_x则相反。如果(x_y+y_x)%2==1,说明不能通过交换构成两个相等的字符串;最后,如果x_y或者y_x是奇数的时候,最小交换步数需要+2。这些规律我也找不出来,我只是欣赏一下,哈哈哈。

代码

class Solution: def minimumSwap(self, s1: str, s2: str) -> int: x_y,y_x=0,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): return res+2 return res

参考文献

​​[LeetCode] Simply Simple Python Solution - with detailed explanation​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 1507. Reformat Date
下一篇:听说你会 Python ?(听说你会来)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~