Minimize length of a given string by removing subsequences forming valid parenthesis | Java program of the above approach ; Function to remove all possible valid bracket subsequences ; Stores indexes of ' ( ' in valid subsequences ; Stores indexes of ' { ' in valid subsequences ; Stores indexes of ' [ ' in valid subsequences ; vis [ i ] : Check if character at i - th index is removed or not ; Mark vis [ i ] as not removed ; Iterate over the characters of string ; If current character is ' ( ' ; If current character is ' { ' ; If current character is ' [ ' ; If current character is ' ) ' and top element of A is ' ( ' ; Mark the top element of A as removed ; Mark current chacracter as removed ; If current character is ' } ' and top element of B is ' { ' ; Mark the top element of B as removed ; Mark current chacracter as removed ; If current character is ' ] ' and top element of B is ' [ ' ; Mark the top element of C as removed ; Mark current chacracter as removed ; Print the remaining characters which is not removed from S ; Driver code ; Given string ; Size of the string ; Function Call
import java . util . * ; public class GFG { static void removeValidBracketSequences ( String str , int N ) { Vector < Integer > A = new Vector < Integer > ( ) ; Vector < Integer > B = new Vector < Integer > ( ) ; Vector < Integer > C = new Vector < Integer > ( ) ; boolean [ ] vis = new boolean [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { vis [ i ] = true ; } for ( int i = 0 ; i < N ; i ++ ) { if ( str . charAt ( i ) == ' ( ' ) { A . add ( i ) ; } else if ( str . charAt ( i ) == ' { ' ) { B . add ( i ) ; } else if ( str . charAt ( i ) == ' [ ' ) { C . add ( i ) ; } else if ( str . charAt ( i ) == ' ) ' && ( A . size ( ) > 0 ) ) { vis [ A . get ( A . size ( ) - 1 ) ] = false ; A . remove ( A . size ( ) - 1 ) ; vis [ i ] = false ; } else if ( str . charAt ( i ) == ' } ' && ( B . size ( ) > 0 ) ) { vis [ B . get ( B . size ( ) - 1 ) ] = false ; B . remove ( B . size ( ) - 1 ) ; vis [ i ] = false ; } else if ( str . charAt ( i ) == ' ] ' && ( C . size ( ) > 0 ) ) { vis [ C . get ( C . size ( ) - 1 ) ] = false ; C . remove ( C . size ( ) - 1 ) ; vis [ i ] = false ; } } for ( int i = 0 ; i < N ; ++ i ) { if ( vis [ i ] ) System . out . print ( str . charAt ( i ) ) ; } } public static void main ( String [ ] args ) { String str = " ( ( ) { ( ) ( { } ) " ; int N = str . length ( ) ; removeValidBracketSequences ( str , N ) ; } }