Smallest string obtained by removing all occurrences of 01 and 11 from Binary String | Set 2 | Java program for the above approach ; Function to find the length of the smallest string possible by removing substrings "01" and "11" ; Stores the length of the smallest string ; Traverse the string S ; If st is greater than 0 and S [ i ] is '1' ; Delete the last character and decrement st by 1 ; Otherwise ; Increment st by 1 ; Return the answer in st ; Driver code ; Input ; Function call
public class GFG_JAVA { static int shortestString ( String S , int N ) { int st = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( st > 0 && S . charAt ( i ) == '1' ) { st -- ; } else { st ++ ; } } return st ; } public static void main ( String [ ] args ) { String S = "1010" ; int N = S . length ( ) ; System . out . println ( shortestString ( S , N ) ) ; } }