Minimum substring reversals required to make given Binary String alternating | Java program for the above approach ; Function to count the minimum number of substrings required to be reversed to make the string S alternating ; Store count of consecutive pairs ; Stores the count of 1 s and 0 s ; Traverse through the string ; Increment 1 s count ; Increment 0 s count ; Increment K if consecutive same elements are found ; Increment 1 s count ; else Increment 0 s count ; Check if it is possible or not ; Otherwise , print the number of required operations ; Driver code ; Function Call
import java . util . * ; import java . lang . * ; class GFG { static int minimumReverse ( String s , int n ) { int k = 0 , l = 0 ; int sum1 = 0 , sum0 = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '1' ) sum1 ++ ; else sum0 ++ ; if ( s . charAt ( i ) == s . charAt ( i - 1 ) && s . charAt ( i ) == '0' ) k ++ ; else if ( s . charAt ( i ) == s . charAt ( i - 1 ) && s . charAt ( i ) == '1' ) l ++ ; } if ( s . charAt ( 0 ) == '1' ) sum1 ++ ; sum0 ++ ; if ( Math . abs ( sum1 - sum0 ) > 1 ) return - 1 ; return Math . max ( k , l ) ; } public static void main ( String [ ] args ) { String S = "10001" ; int N = S . length ( ) ; System . out . print ( minimumReverse ( S , N ) ) ; } }