Length of the longest valid substring | C # program to find length of the longest valid substring ; method to get length of the longest valid ; Create a stack and push - 1 as initial index to it . ; Initialize result ; Traverse all characters of given string ; If opening bracket , push index of it ; If closing bracket , i . e . , str [ i ] = ' ) ' ; Pop the previous opening bracket 's index ; Check if this length formed with base of current valid substring is more than max so far ; If stack is empty . push current index as base for next valid substring ( if any ) ; Driver Code ; Function call ; Function call
using System ; using System . Collections . Generic ; class GFG { public static int findMaxLen ( string str ) { int n = str . Length ; Stack < int > stk = new Stack < int > ( ) ; stk . Push ( - 1 ) ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ( ' ) { stk . Push ( i ) ; } else { if ( stk . Count > 0 ) stk . Pop ( ) ; if ( stk . Count > 0 ) { result = Math . Max ( result , i - stk . Peek ( ) ) ; } else { stk . Push ( i ) ; } } } return result ; } public static void Main ( string [ ] args ) { string str = " ( ( ( ) ( ) " ; Console . WriteLine ( findMaxLen ( str ) ) ; str = " ( ) ( ( ) ) ) ) ) " ; Console . WriteLine ( findMaxLen ( str ) ) ; } }