Find a valid parenthesis sequence of length K from a given valid parenthesis sequence | Java program for the above approach ; Function to find the subsequence of length K forming valid sequence ; Stores the resultant String ; Check whether character at index i is visited or not ; Traverse the String ; Push index of open bracket ; Pop and mark visited ; Increment count by 2 ; Append the characters and create the resultant String ; Return the resultant String ; Driver Code ; Function call
import java . util . * ; class GFG { static String findString ( String s , int k ) { int n = s . length ( ) ; String ans = " ▁ " ; Stack < Integer > st = new Stack < > ( ) ; boolean [ ] vis = new boolean [ n ] ; Vector < boolean > vis ( n , false ) ; int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( s . charAt ( i ) == ' ( ' ) { st . add ( i ) ; } if ( count < k && s . charAt ( i ) == ' ) ' ) { vis [ st . peek ( ) ] = true ; st . pop ( ) ; vis [ i ] = true ; count += 2 ; } } for ( int i = 0 ; i < n ; ++ i ) { if ( vis [ i ] == true ) { ans += s . charAt ( i ) ; } } return ans ; } public static void main ( String [ ] args ) { String s = " ( ) ( ) ( ) " ; int K = 2 ; System . out . print ( findString ( s , K ) ) ; } }