Minimum operand to generate alternate binary string

Minimum operand to generate alternate binary string

Give you a string s consisting of only the characters '0' and '1'.
In one step, you can change any '0' into '1', or change '1' into '0'.

Alternate character string is defined as:
if there is no situation where two adjacent characters are equal in the character string, then the character string is an alternate character string.
For example, the string "010" is an alternate string, but the string "0100" is not.
Returns the minimum number of operations required to make s an alternate string. Example of
the 228th weekly match
:

Input: s = "0100"
Output: 1
Explanation: If the last character is changed to '1', s becomes "0101", that is, it conforms to the alternate string definition.

Input: s = "10"
Output: 0
Explanation: s is already an alternate string.

Input: s = "1111"
Output: 2
Explanation: It takes 2 steps to get "0101" or "1010".

The final form of the string required for the question is nothing more than "010101" or "101010", so we can calculate how many different numbers there are between the original string and the final form, and get two operands. The smaller one is the answer.

Comparative method

Pay attention to the comparison, record the operands separately, and return the smaller value.

class Solution {
    
    
public:
	int minOperations(string s) {
    
    
		int n = s.length();
		int ans1 = 0;
		int ans2 = 0;
		for (int i = 0; i < n; i++) {
    
    
			if ((i % 2) && s[i] == '1' || !(i % 2) && s[i] == '0')
				ans1++;
			if ((i % 2) && s[i] == '0' || !(i % 2) && s[i] == '1')
				ans2++;
		}
		return min(ans1, ans2);
	}
};

Bit operation

class Solution {
    
    
public:
	int minOperations(string s) {
    
    
		int n = s.length();
		int ans1 = 0;//记录第一种情况所需反转次数
		int flag = (s[0] - '0');
		for (int i = 0; i < n; i++) {
    
    
			ans1 += flag ^ (s[i] - '0');
			flag = !flag;
		}
		int ans2 = 0;//记录第二种情况所需反转次数
		flag = !(s[0] - '0');
		for (int i = 0; i < n; i++) {
    
    
			ans2 += flag ^ (s[i] - '0');
			flag = !flag;//标准旗帜反转
		}
		return min(ans1, ans2);
	}
};

Guess you like

Origin blog.csdn.net/Genius_bin/article/details/113873415