Find a valid parenthesis sequence of length K from a given valid parenthesis sequence | C # 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
using System ; using System . Collections . Generic ; class GFG { static String findString ( String s , int k ) { int n = s . Length ; String ans = " ▁ " ; Stack < int > st = new Stack < int > ( ) ; bool [ ] vis = new bool [ n ] ; List < bool > vis ( n , false ) ; int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( s [ i ] == ' ( ' ) { st . Push ( i ) ; } if ( count < k && s [ 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 [ i ] ; } } return ans ; } public static void Main ( String [ ] args ) { String s = " ( ) ( ) ( ) " ; int K = 2 ; Console . Write ( findString ( s , K ) ) ; } }