Count of groups of consecutive 1 s in a given Binary String | Java program for the above approach ; Function to find the number of the groups of 1 s only in the binary string ; Stores number of groups of 1 s ; Initialization of the stack ; Traverse the string S ; If S [ i ] is '1' ; Otherwise ; If st is empty ; If st is not empty ; Return answer ; Driver code ; Input ; Function call
import java . util . Stack ; class GFG { static int groupsOfOnes ( String S , int N ) { int count = 0 ; Stack < Integer > st = new Stack < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( S . charAt ( i ) == '1' ) st . push ( 1 ) ; else { if ( ! st . empty ( ) ) { count ++ ; while ( ! st . empty ( ) ) { st . pop ( ) ; } } } } if ( ! st . empty ( ) ) count ++ ; return count ; } public static void main ( String [ ] args ) { String S = "100110111" ; int N = S . length ( ) ; System . out . println ( groupsOfOnes ( S , N ) ) ; } }