Longer Contiguous Segments of Ones than Zeros

Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise.

  • For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3.

Note that if there are no 0s, then the longest contiguous segment of 0s is considered to have length 0. The same applies if there are no 1s.

Example 1:

Input: s = "1101"
Output: true
Explanation:
The longest contiguous segment of 1s has length 2: "1101"
The longest contiguous segment of 0s has length 1: "1101"
The segment of 1s is longer, so return true.

Example 2:

Input: s = "111000"
Output: false
Explanation:
The longest contiguous segment of 1s has length 3: "111000"
The longest contiguous segment of 0s has length 3: "111000"
The segment of 1s is not longer, so return false.

Approach

C++

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

bool checkZeroOnes(string s)
{
    int n = s.size();
    int maxOnes = 0maxZeros = 0;

    int i = 0;

    while (i < n)
    {
        int ones = 0zeros = 0;
        while (i < n && s[i] == '1')
        {
            ones++;
            i++;
        }
        while (i < n && s[i] == '0')
        {
            zeros++;
            i++;
        }
        maxOnes = max(onesmaxOnes);
        maxZeros = max(zerosmaxZeros);
    }
    if (maxOnes > maxZeros)
        return true;
    return false;
}

int main()
{
    string s = "1101";

    if (checkZeroOnes(s))
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}


No comments:

Post a Comment