text: Count ways to split a Binary String into three substrings having equal count of zeros | Java program for above approach ; Function to calculate the number of ways to split ; Calculating the total number of zeros ; Case1 If total count of zeros is not divisible by 3 ; Case2 if total count of zeros is zero ; Number of zeros in each substring ; Initialising zero to the number of ways for first and second cut ; Initializing the count ; Traversing from the beginning ; Incrementing the count if the element is '0' ; Incrementing the ways for the 1 st cut if count is equal to zeros required in each substring ; Incrementing the ways for the 2 nd cut if count is equal to 2 * ( zeros required in each substring ) ; Total number of ways to split is multiplication of ways for the 1 st and 2 nd cut ; Driver Code ; Function Call
code: import java . util . * ; class GFG { static int splitstring ( String s ) { int n = s . length ( ) ; int zeros = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( s . charAt ( i ) == '0' ) zeros ++ ; if ( zeros % 3 != 0 ) return 0 ; if ( zeros == 0 ) return ( ( n - 1 ) * ( n - 2 ) ) / 2 ; int zerosInEachSubstring = zeros / 3 ; int waysOfFirstCut = 0 ; int waysOfSecondCut = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '0' ) count ++ ; if ( count == zerosInEachSubstring ) waysOfFirstCut ++ ; else if ( count == 2 * zerosInEachSubstring ) waysOfSecondCut ++ ; } return waysOfFirstCut * waysOfSecondCut ; } public static void main ( String args [ ] ) { String s = "01010" ; System . out . println ( " The ▁ number ▁ of ▁ " + " ways ▁ to ▁ split ▁ is ▁ " + splitstring ( s ) ) ; } }