text: Count of occurrences of a "1(0 + ) 1" pattern in a string | Java 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: public class GFG { static int countPattern ( String str ) { int len = str . length ( ) ; boolean oneSeen = false ; for ( int i = 0 ; i < len ; i ++ ) { char getChar = str . charAt ( i ) ; if ( getChar == '1' && oneSeen == true ) { if ( str . charAt ( i - 1 ) == '0' ) count ++ ; } if ( getChar == '1' && oneSeen == false ) oneSeen = true ; if ( getChar != '0' && str . charAt ( i ) != '1' ) oneSeen = false ; } return count ; } public static void main ( String [ ] args ) { String str = "100001abc101" ; System . out . println ( countPattern ( str ) ) ; } }