Minimize length of a string by removing pairs of consecutive increasing or decreasing digits | C ++ program for the above approach ; Function to find the minimum length of the string possible after removing pairs of consecutive digits ; Initialize the stack st ; Traverse the string S ; If the stack is empty ; Otherwise ; Get the top character of the stack ; If cha and top are consecutive digits ; Otherwise , push the character ch ; Print the size of the stack ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( string S ) { stack < char > st ; for ( auto ch : S ) { if ( st . empty ( ) ) st . push ( ch ) ; else { char top = st . top ( ) ; if ( abs ( ch - top ) == 1 ) st . pop ( ) ; else { st . push ( ch ) ; } } } return st . size ( ) ; } int main ( ) { string S = "12213" ; cout << minLength ( S ) ; return 0 ; }