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 :
Input: s = "0100" Output: 1
Explanation: If you change the last character to '1', s will be "0101", which is alternating
SOLUTION
int minOperations(string s)
{
int n = s.length();
if (n <= 1)
return 0;
int c1 = 0;
int c0 = 0;
for (int i = 0; i < n; i++)
{
if (i % 2)
{
if (s[i] == '1')
c0++;
else
c1++;
}
else
{
if (s[i] == '0')
c0++;
else
c1++;
}
}
return min(c0, c1);
}
Thank You...
No comments:
Post a Comment