Check Consecutive Occurrences of '1' in Binary String using C++



Here we will see another interesting problem. We have to write a code that accepts a string, which has following criteria.

  • Every group of consecutive 1s, must be of length 2
  • every group of consecutive 1s must appear after 1 or more 0s

Suppose there is a string like 0110, this is valid string, whether 001110, 010 are not valid

Here the approach is simple. we have to find the occurrences of 1, and check whether it is a part of sub-string 011 or not. If condition fails, for any substring then return false, otherwise true.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isValidStr(string str) {
   int n = str.length();
   int index = find(str.begin(), str.end(), '1') - str.begin();
   if (index == 0) //when the string starts with 1, then return false
   return false;
   while (index <= n - 1) {
      if (str[index - 1] != '0') // If 1 doesn't appear after an 0
         return false;
      if (index + 1 < n && str[index + 1] != '1') // If '1' is not succeeded by another '1'
         return false;
      if (index + 2 < n && str[index + 2] == '1') // If sub-string is of the type "0111"
         return false;
      if (index == n - 1) // If str ends with a single 1
         return false;
      index = find(str.begin() + index + 2, str.end(), '1') - str.begin();
   }
   return true;
}
int main() {
   string str = "011000110110";
   if(isValidStr(str)){
      cout << str << " is a valid string";
   } else {
      cout << str << " is NOT a valid string";
   }
}

Output

011000110110 is a valid string
Updated on: 2019-09-25T14:03:49+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements