Minimize a binary string by repeatedly removing even length substrings of same characters | Java program for the above approach ; Recursive function to print stack elements from bottom to top without changing their order ; If stack is empty ; Pop top element of the stack ; Recursively call the function PrintStack ; Print the stack element from the bottom ; Push the same element onto the stack to preserve the order ; Function to minimize binary String by removing subStrings consisting of same character ; Declare a stack of characters ; Push the first character of the String into the stack ; Traverse the String s ; If Stack is empty ; Push current character into the stack ; Check if the current character is same as the top of the stack ; If true , pop the top of the stack ; Otherwise , push the current element ; Print stack from bottom to top ; Driver Code
import java . util . * ; class GFG { static void PrintStack ( Stack < Character > s ) { if ( s . isEmpty ( ) ) return ; char x = s . peek ( ) ; s . pop ( ) ; PrintStack ( s ) ; System . out . print ( x ) ; s . add ( x ) ; } static void minString ( String s ) { Stack < Character > Stack = new Stack < Character > ( ) ; Stack . add ( s . charAt ( 0 ) ) ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( Stack . isEmpty ( ) ) { Stack . add ( s . charAt ( i ) ) ; } else { if ( Stack . peek ( ) == s . charAt ( i ) ) { Stack . pop ( ) ; } else { Stack . push ( s . charAt ( i ) ) ; } } } PrintStack ( Stack ) ; } public static void main ( String [ ] args ) { String str = "101001" ; minString ( str ) ; } }