1758. Minimum Changes To Make Alternating Binary String

```java
class Solution {
    public int minOperations(String s) {
        int result = Integer.MAX_VALUE;

        result = Math.min(result, cal(s, '0'));
        result = Math.min(result, cal(s, '1'));
        return result;
    }
    private int cal(String s, char pre) {
        int count = 0;
        if (pre != s.charAt(0)) {
            count = 1;
        }
        for (int i = 1; i < s.length(); i++) {
            if ((pre == s.charAt(i))) {
                count++;
            }
            if (pre == '0') {
                pre = '1'; // 1
            } else {
                pre = '0';
            }
        }
        return count;
    }
}

/**
T: O(n)
S: O(1)
"10010100"
 01.    1 

 */
```

more simple idea and code:

```java
class Solution {
    public int minOperations(String s) {
        int n = s.length();
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) - '0' != i%2) {
                count++;
            }
        }
        return Math.min(n - count, count);
    }
}

/**
T: O(n)
S: O(1)
 010101
"10010100"
 

 can use index%2 as the "seq" 010101, and cal. "count"
 and in another side, 101010
 only need to use n - count

 so result = Math.min(n - count, count);

 */
```

Last updated