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.
Approach
Java
public class MinChangeAlternateString {public static void main(String[] args) {String s = "0100";System.out.println(minOperations(s));}static int minOperations(String s) {int ones = 0;int n = s.length();for (int i = 0; i < n; i++) {if (i % 2 == 1) {if (s.charAt(i) != '1')ones += 1;} else {if (s.charAt(i) != '0')ones += 1;}}return Math.min(ones, n - ones);}}
C++
#include <bits/stdc++.h>using namespace std;int minOperations(string s){int ones = 0;int n = s.size();for (int i = 0; i < n; i++){ones += i & 1 ? s[i] != '1' : s[i] != '0';}return min(ones, n - ones);}int main(){string s = "0100";cout << minOperations(s) << "\n";return 0;}
No comments:
Post a Comment