
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Program to count substrings with all 1s in binary string in Python
- Count of substrings of a binary string containing K ones in C++
- Count of total anagram substrings in C++
- Count all Prime Length Palindromic Substrings in C++
- Program to count number of palindromic substrings in Python
- Program to count number of homogenous substrings in Python
- Binary String With Substrings Representing 1 To N in C++
- Find the count of substrings in alphabetic order in C++
- Count of Palindromic substrings in an Index range in C++
- Counting even decimal value substrings in a binary string in C++
- Count substrings with same first and last characters in C++
- Program to count maximum score from removing substrings in Python
- Program to count number of distinct substrings in s in Python
- Count number of substrings with exactly k distinct characters in C++
- Program to count substrings that differ by one character in Python

Advertisements