Count of non | C ++ implementation of the approach ; Function to return the count of required non - overlapping sub - strings ; To store the required count ; If "010" matches the sub - string starting at current index i ; If "101" matches the sub - string starting at current index i ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countSubStr ( string s , int n ) { int count = 0 ; for ( int i = 0 ; i < n - 2 ; ) { if ( s [ i ] == '0' && s [ i + 1 ] == '1' && s [ i + 2 ] == '0' ) { count ++ ; i += 3 ; } else if ( s [ i ] == '1' && s [ i + 1 ] == '0' && s [ i + 2 ] == '1' ) { count ++ ; i += 3 ; } else { i ++ ; } } return count ; } int main ( ) { string s = "10101010101" ; int n = s . length ( ) ; cout << countSubStr ( s , n ) ; return 0 ; }