[LeetCode] Minimum Changes To Make Alternating Binary String

1758. Minimum Changes To Make Alternating Binary String

You are given a string s consisting only of the characters ‘0’ and ‘1’. In one operation, you can change any ‘0’ to ‘1’ or vice versa.

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

Return the minimum number of operations needed to make s alternating.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int minOperations(string s) {
bool type1 = false, type2 = true;
int diff1 = 0, diff2 = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '0') {
if(type1)
diff1++;
if(type2)
diff2++;
} else {
if(!type1)
diff1++;
if(!type2)
diff2++;
}
type1 ^= true;
type2 ^= true;
}
return min(diff1, diff2);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/14/PS/LeetCode/minimum-changes-to-make-alternating-binary-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.