Convert given Binary string S to all 1 s by changing all 0 s to 1 s in range [ i + 1 , i + K ] if S [ i ] is 1 | Java program for the above approach ; Function to check whether all 0 s in the string can be changed into 1 s ; Store the count of 0 s converted for the last occurrence of 1 ; Declere a stack ; Traverse the string , S ; If stack is empty ; There is no 1 that can change this 0 to 1 ; Push 1 into the stack ; The last 1 has reached its limit ; New 1 has been found which can now change at most K 0 s ; If flag is 1 , print " YES " else print " NO " ; Driver code ; Given Input ; Function call
import java . util . * ; class GFG { static void changeCharacters ( String S , int N , int K ) { int flag = 1 ; int count = 0 ; Stack < Character > st = new Stack < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( st . empty ( ) ) { if ( S . charAt ( i ) == '0' ) { flag = 0 ; break ; } count = 0 ; st . push ( S . charAt ( i ) ) ; } else { if ( S . charAt ( i ) == '0' ) { count ++ ; if ( count == K ) { st . pop ( ) ; count = 0 ; } } else { count = 0 ; } } } if ( flag == 1 ) System . out . print ( " YES " ) ; else System . out . print ( " NO " ) ; } public static void main ( String args [ ] ) { String S = "100100" ; int N = S . length ( ) ; int K = 2 ; changeCharacters ( S , N , K ) ; } }