Beautiful Binary String

Alice has a binary string. She thinks a binary string is beautiful if and only if it doesn't contain the substring "010".

In one step, Alice can change a 0 to a 1 or vice versa. 

Count and print the minimum number of steps needed to make Alice see the string as beautiful.


Example:

Input:  n=10,s="0100101010"
Output: 3

Approach

Java

public class BeautifulBinaryString {
    public static void main(String[] args) {
        String s = "0100101010";
        System.out.println(beautifulBinaryString(s));
    }

    static int beautifulBinaryString(String s) {
        int n = s.length();
        char ch[] = s.toCharArray();
        if (n < 3)
            return 0;
        else {
            int cnt = 0;
            for (int i = 0; i < n - 2; i++) {
                if (ch[i] == '0' && ch[i + 1] == '1'
                     && ch[i + 2] == '0') {
                    cnt++;
                    ch[i + 2] = '1';
                }
            }
            return cnt;
        }
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int beautifulBinaryString(string s)
{
    int n = s.size();
    if (n < 3)
        return 0;
    else
    {
        int cnt = 0;
        for (int i = 0i < n - 2i++)
        {
            if (s[i] == '0' && s[i + 1] == '1' 
                    && s[i + 2] == '0')
            {
                cnt++;
                s[i + 2] = '1';
            }
        }
        return cnt;
    }
}
int main()
{
    int n = 10;

    string s = "0100101010";
    cout << beautifulBinaryString(s);
    return 0;
}


No comments:

Post a Comment