text: Count of occurrences of a "1(0 + ) 1" pattern in a string | C ++ program to calculate number of times the pattern occurred in given string ; Returns count of occurrences of "1(0 + ) 1" int str . ; int count = 0 ; Initialize result ; Check if encountered '1' forms a valid pattern as specified ; if 1 encountered for first time set oneSeen to 1 ; Check if there is any other character other than '0' or '1' . If so then set oneSeen to 0 to search again for new pattern ; Driver program to test above function
code: #include <iostream> NEW_LINE using namespace std ; int countPattern ( string str ) { int len = str . size ( ) ; bool oneSeen = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '1' && oneSeen == 1 ) if ( str [ i - 1 ] == '0' ) count ++ ; if ( str [ i ] == '1' && oneSeen == 0 ) { oneSeen = 1 ; continue ; } if ( str [ i ] != '0' && str [ i ] != '1' ) oneSeen = 0 ; } return count ; } int main ( ) { string str = "100001abc101" ; cout << countPattern ( str ) ; return 0 ; }