Check if K '0' s can be flipped such that Binary String contains no pair of adjacent '1' s | package whatever import java . io . * ; class GFG { Function to check if k '0' s can be flipped such that the string does not contain any pair of adjacent '1' s ; Store the count of flips ; Variable to iterate the string ; Iterate over characters of the string ; If the current character is '1' , increment i by 2 ; Otherwise , 3 cases arises ; If the current index is the starting index ; If next character is '0' ; Increment i by 1 ; If the current index is the last index ; If previous character is '0' ; For remaining characters ; If both the adjacent characters are '0' ; If cnt is at least K , print " Yes " ; Otherwise , print " No " ; Driver code
public static void canPlace ( String s , int n , int k ) { int cnt = 0 ; int i = 0 ; while ( i < n ) { if ( s . charAt ( i ) == '1' ) { i += 2 ; } else { if ( i == 0 ) { if ( s . charAt ( i + 1 ) == '0' ) { cnt ++ ; i += 2 ; } else i ++ ; } else if ( i == n - 1 ) { if ( s . charAt ( i - 1 ) == '0' ) { cnt ++ ; i += 2 ; } else i ++ ; } else { if ( s . charAt ( i + 1 ) == '0' && s . charAt ( i - 1 ) == '0' ) { cnt ++ ; i += 2 ; } else i ++ ; } } } if ( cnt >= k ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } public static void main ( String [ ] args ) { String S = "10001" ; int K = 1 ; int N = 5 ; canPlace ( S , N , K ) ; } }