Minimum Swaps to Make Strings Equal LeetCode solution in Python

1
class Solution:
2
def minimumSwap(self, s1: str, s2: str) -> int:
3
h = defaultdict(int)
4
count = 0 # variable to keep track of the number of mismatches; it is impossible to make strings equal if count is odd
5
for i in range(len(s1)):
6
if s1[i] != s2[i]:
7
count += 1
8
h[s1[i]] += 1
9
if count % 2 != 0:
10
return -1
11
res, a, b = 0, h["x"], h["y"]
12
res += a // 2 + b // 2
13
if a % 2 == 0:
14
return res
15
return res + 2

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0