Count Binary Substrings in C++


Suppose we have a string s, we have to find the count of contiguous substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. If substrings occur multiple times are counted the number of times they occur.

So, if the input is like "11001100", then the output will be 6, as the substrings are "1100", "10","0011", "01", "1100", "10".

To solve this, we will follow these steps −

  • Define an array cnt of size 2 and fill this with 0
  • res := 0
  • for initialize i := 0, when i < length of s, update (increase i by 1), do −
    • num := s[i] - ASCII of '0'
    • if i is same as 0 or s[i] is not equal to s[i - 1], then −
      • cnt[num] := 0
    • (increase cnt[num] by 1)
    • if cnt[num] <= cnt[1 - num], then −
      • (increase res by 1)
  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int countBinarySubstrings(string s) {
      int cnt[2] = { 0 };
      int res = 0;
      for (int i = 0; i < s.length(); ++i) {
         int num = s[i] - '0';
         if (i == 0 || s[i] != s[i - 1])
            cnt[num] = 0;
         ++cnt[num];
         if (cnt[num] <= cnt[1 - num])
            ++res;
      }
      return res;
   }
};
main(){
   Solution ob;
   cout << (ob.countBinarySubstrings("11001100"));
}

Input

"11001100"

Output

6

Updated on: 04-Jul-2020

664 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements