Minimum Number of Swaps to Make the Binary String Alternating LeetCode solution in Python

1
class Solution:
2
def minSwaps(self, st: str) -> int:
3

4
def swap(st, c):
5
n = len(st)
6
mis = 0
7
for i in range(n):
8
if i % 2 == 0 and st[i] != c:
9
mis += 1
10
if i % 2 == 1 and st[i] == c:
11
mis += 1
12
return mis // 2
13

14
dic = Counter(st)
15
z = dic["0"]
16
o = dic["1"]
17
res = 0
18
if abs(z - o) > 1:
19
return -1
20
elif z > o:
21
res = swap(st, "0")
22
elif o > z:
23
res = swap(st, "1")
24
else:
25
res = min(swap(st, "0"), swap(st, "1"))
26

27
return res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0