Created
November 4, 2023 20:21
-
-
Save primaryobjects/b911c62d19d8861535af3d1e2617e730 to your computer and use it in GitHub Desktop.
Minimum changes to make alternating binary string https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/description/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Solution { | |
| public int MinOperations(string s) { | |
| // Using original first bit. | |
| int count1 = 0; | |
| char prev1 = s[0]; | |
| // Using opposite first bit. | |
| int count2 = 1; | |
| char prev2 = prev1 == '0' ? '1' : '0'; | |
| for (int i=1; i<s.Length; i++) | |
| { | |
| // Check first attempt with original first bit. | |
| if (prev1 == s[i]) | |
| { | |
| // Flip bit. | |
| prev1 = prev1 == '0' ? '1' : '0'; | |
| count1++; | |
| } | |
| else | |
| { | |
| prev1 = s[i]; | |
| } | |
| // Check second attempt with first bit flipped. | |
| if (prev2 == s[i]) | |
| { | |
| // Flip bit. | |
| prev2 = prev2 == '0' ? '1' : '0'; | |
| count2++; | |
| } | |
| else | |
| { | |
| prev2 = s[i]; | |
| } | |
| } | |
| return Math.Min(count1, count2); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 1758. Minimum Changes To Make Alternating Binary String | |
| Solved | |
| Easy | |
| Topics | |
| Companies | |
| Hint | |
| 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". | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment