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

1
class Solution {
2
public int minSwaps(String s) {
3
int cntZero = 0, cntOne = 0;
4
for (char ch : s.toCharArray()) {
5
if (ch == '0') cntZero++;
6
else cntOne++;
7
}
8

9
// Invalid
10
if (Math.abs(cntOne - cntZero) > 1) return -1;
11

12
if (cntOne > cntZero) { // one must be at even posotion
13
return countSwaps(s, '1');
14
} else if (cntOne < cntZero) {
15
return countSwaps(s, '0'); // zero must be at even position
16
}
17

18
return Math.min(countSwaps(s, '0'), countSwaps(s, '1'));
19
}
20

21
// wrong count
22
private int countSwaps(String s, char start) {
23
int wrongPosition = 0;
24
for (int i = 0; i < s.length(); i += 2) {
25
if (s.charAt(i) != start) wrongPosition++;
26
}
27
return wrongPosition;
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0