Minimum Changes To Make Alternating Binary String

给一个string, 里面有0和1, 求最少替换(0->1 or 1->0)的位置的个数, 使得string变成0和1互相不相邻的string.

这个题想下就知道, 互相不相邻的string要不然是: 0101010101 要不然是1010101010. 所以只需要考虑2个情况即可.

class Solution {
    public int minOperations(String s) {
        int zero = 0;
        int next = 0;
        for(char c : s.toCharArray()){
            if(c - '0' != next){
                zero++;  
            }
            if(next == 0)
                next = 1;
            else
                next = 0;
        }
        int one = 0;
        next = 1;
        for(char c : s.toCharArray()){
            if(c - '0' != next){
                one++;  
            }
            if(next == 0)
                next = 1;
            else
                next = 0;
        }
        if(zero == 0 && one == 0)
            return 0;
        else
            return Math.min(zero, one);
    }
}