Find all the patterns of "1(0 + ) 1" in a given string | SET 1 ( General Approach ) | Java Code to count 1 ( 0 + ) 1 patterns in a string ; Function to count patterns ; Variable to store the last character ; We found 0 and last character was '1' , state change ; After the stream of 0 ' s , ▁ we ▁ ▁ got ▁ a ▁ ' 1 ',counter incremented ; Last character stored ; Driver Code
import java . io . * ; class GFG { static int patternCount ( String str ) { char last = str . charAt ( 0 ) ; int i = 1 , counter = 0 ; while ( i < str . length ( ) ) { if ( str . charAt ( i ) == '0' && last == '1' ) { while ( str . charAt ( i ) == '0' ) i ++ ; if ( str . charAt ( i ) == '1' ) counter ++ ; } last = str . charAt ( i ) ; i ++ ; } return counter ; } public static void main ( String [ ] args ) { String str = "1001ab010abc01001" ; System . out . println ( patternCount ( str ) ) ; } }