Welcome back to the leetcode daily problem, 24th of December.
Solution:
We can see that there are two cases for alternating: strings with one or zero appear at the even indices, and vice versa. For example : 101010, 010101, etc.
We can count the one or zero at their respective indexes, and the answer will be the minimum of two result variables.
Code:
class Solution {
public:
int minOperations(string s) {
int one = 0, zero = 0;
const int n = (int) s.size();
for(int i = 0; i < n; ++i) {
if(i % 2 == s[i] - '0')
++zero;
else
++one;
}
return min(zero, one);
}
};