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.

 

Example 1:

Input: s = "0100"
Output: 1
Explanation: If you change the last character to '1', s will be "0101", which is alternating.
Example 2:

Input: s = "10"
Output: 0
Explanation: s is already alternating.
Example 3:

Input: s = "1111"
Output: 2
Explanation: You need two operations to reach "0101" or "1010".
 

Constraints:

1 <= s.length <= 104
s[i] is either '0' or '1'.

这题一开始走入了误区,想着先把字符串分割为交错的字符串,然后看看如何变更能使得满足题意的条件,导致这个题目变得相当的复杂。

后来想了想,由于只有0和1,所以目的的字符串是固定的,有两种,一个是0在头部,另一个则是1。所以我们只需要和结果字符串做比较,看看变为该字符串需要花费的次数,取最小即可。


class MinimumChangesToMakeAlternatingBinaryString : public Solution {
public:
    void Exec() {
        
    }
    int minOperations(string s) {
        if (s.size() < 2) return 0;
        int count0 = 0, count1 = 0;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] != ((i % 2 == 0) ? '0' : '1')) count0++;
            if (s[i] != ((i % 2 == 1) ? '0' : '1')) count1++;
        }
        return std::min(count0, count1);
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day