Number of flips to make binary string alternate | Set 1 | Java program to find minimum number of flip to make binary string alternate ; Utility method to flip a character ; Utility method to get minimum flips when alternate string starts with expected char ; if current character is not expected , increase flip count ; flip expected character each time ; method return minimum flip to make binary string alternate ; return minimum of following two 1 ) flips when alternate string starts with 0 2 ) flips when alternate string starts with 1 ; Driver code to test above method
class GFG { public static char flip ( char ch ) { return ( ch == '0' ) ? '1' : '0' ; } public static int getFlipWithStartingCharcter ( String str , char expected ) { int flipCount = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) != expected ) flipCount ++ ; expected = flip ( expected ) ; } return flipCount ; } public static int minFlipToMakeStringAlternate ( String str ) { return Math . min ( getFlipWithStartingCharcter ( str , '0' ) , getFlipWithStartingCharcter ( str , '1' ) ) ; } public static void main ( String args [ ] ) { String str = "0001010111" ; System . out . println ( minFlipToMakeStringAlternate ( str ) ) ; } }