Problem Statement:
You are given a binary string, you need to return true if the longest contiguous sequence of 1s is greater than the longest contiguous sequence of 0.
Example
Input: s = “1101”
Output: true
Beause longest continious segment of 1 is 2, and 0 is 1.
Solution
The solution is very simple.
We can do it in linear time.
We take 2 counters “ones”, “zeros”
Each time you encounter 1, increment the “ones” count and make “zeros” as zero.
else
do the reverse.
For every iteration, save the maxOne and maxZero and return the result.
Solution in C++
#include <algorithm>
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
bool check_zero_ones(string s)
{
int maxOnes=0,maxZeros=0,ones=0,zeros=0,n=s.length();
for(int i=0;i<n;i++)
{
if(s[i]=='1') ones++,zeros=0;
else zeros++,ones=0;
maxOnes=max(maxOnes,ones);
maxZeros=max(maxZeros,zeros);
}
return maxOnes>maxZeros;
}
int main()
{
string s1 = "111110011";
if(check_zero_ones(s1)){
cout<<"True"<<endl;
} else {
cout<<"False"<<endl;
}
return 0;
}
Output:
True