Minimize a binary string by repeatedly removing even length substrings of same characters | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void PrintStack ( stack < char > s ) { if ( s . empty ( ) ) return ; char x = s . top ( ) ; s . pop ( ) ; PrintStack ( s ) ; cout << x ; s . push ( x ) ; } void minString ( string s ) { stack < char > Stack ; Stack . push ( s [ 0 ] ) ; for ( int i = 1 ; i < s . size ( ) ; i ++ ) { if ( Stack . empty ( ) ) { Stack . push ( s [ i ] ) ; } else { if ( Stack . top ( ) == s [ i ] ) { Stack . pop ( ) ; } else { Stack . push ( s [ i ] ) ; } } } PrintStack ( Stack ) ; } int main ( ) { string str = "101001" ; minString ( str ) ; return 0 ; }