[LeetCode] Minimum Number of Swaps to Make the Binary String Alternating

1864. Minimum Number of Swaps to Make the Binary String Alternating

Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.

The string is called alternating if no two adjacent characters are equal. For example, the strings “010” and “1010” are alternating, while the string “0100” is not.

Any two characters may be swapped, even if they are not adjacent.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int chk(string& s, int start) {
int res = 0;
for(auto& c : s) {
if((c & 0b1111) != start) res++;
start ^= 1;
}
return (res + 1)>>1;
}
public:
int minSwaps(string s) {
int zero = 0, one = 0, res = 0;
list<int> One{s[0] & 0b1111};
for(int i = 0; i < s.size(); i++) {
if(s[i] == '1') one++;
else zero++;
}
if(abs(zero - one) > 1) return -1;
return one > zero ? chk(s, 1) : zero > one ? chk(s, 0) : min(chk(s, 1), chk(s, 0));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/16/PS/LeetCode/minimum-number-of-swaps-to-make-the-binary-string-alternating/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.