Minimize length by removing subsequences forming valid parenthesis from a given string | C ++ program for the above approach ; Function to find the minimum count of remaining characters left into the string by removing the valid subsequences ; Length of the string ; Stores opening parenthesis ' ( ' of the given string ; Stores square parenthesis ' [ ' of the given string ; Stores count of opening parenthesis ' ( ' in valid subsequences ; Stores count of opening parenthesis ' [ ' in valid subsequences ; Iterate over each characters of S ; If current character is ' [ ' ; insert into stack ; If i is equal to ' ] ' ; If stack is not empty and top element of stack is ' [ ' ; Remove top element from stack ; Update squareCount ; If current character is ' ( ' ; Insert into stack ; If i is equal to ' ) ' ; If stack is not empty and top element of stack is ' ( ' ; Remove top element from stack ; Update roundCount ; Print the minimum number of remaining characters left into S ; Driver code ; input string ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void deleteSubseq ( string s ) { int N = s . size ( ) ; stack < char > roundStk ; stack < char > squareStk ; int roundCount = 0 ; int squareCount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == ' [ ' ) { squareStk . push ( s [ i ] ) ; } else if ( s [ i ] == ' ] ' ) { if ( squareStk . size ( ) != 0 && squareStk . top ( ) == ' [ ' ) { squareStk . pop ( ) ; squareCount += 1 ; } } else if ( s [ i ] == ' ( ' ) { roundStk . push ( s [ i ] ) ; } else { if ( roundStk . size ( ) != 0 && squareStk . top ( ) == ' ( ' ) { squareStk . pop ( ) ; roundCount += 1 ; } } } cout << ( N - ( 2 * squareCount + 2 * roundCount ) ) ; } int main ( ) { string s = " [ ] ] ) ( [ " ; deleteSubseq ( s ) ; }