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:
Example 2:
Example 3:
Example 4:
Constraints:
- 1 <= s1.length, s2.length <= 1000
- s1, 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。这些规律我也找不出来,我只是欣赏一下,哈哈哈。
代码
参考文献
[LeetCode] Simply Simple Python Solution - with detailed explanation