LeetCode 1247. Minimum Swaps to Make Strings Equal
考点 | 难度 |
---|---|
Greedy | Easy |
题目
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.
思路
xx和yy需要swap一次, xy和yx 需要swap两次
答案
class Solution(object):
def minimumSwap(self, s1, s2):
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
# Both x_y and y_x count shall either be even or odd to get the result.
# x_y + y_x should be even
res = x_y // 2
res += y_x // 2
if x_y % 2 == 1:
res += 2
# If there count is odd i.e. we have "xy" and "yx" situation
# so we need 2 more swaps to make them equal
return res