Length of the longest valid substring | C ++ program to find length of the longest valid substring ; Initialize curMax to zero ; Iterate over the string starting from second index ; Driver code ; Function call ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxLen ( string s ) { if ( s . length ( ) <= 1 ) return 0 ; int curMax = 0 ; vector < int > longest ( s . size ( ) , 0 ) ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == ' ) ' && i - longest [ i - 1 ] - 1 >= 0 && s [ i - longest [ i - 1 ] - 1 ] == ' ( ' ) { longest [ i ] = longest [ i - 1 ] + 2 + ( ( i - longest [ i - 1 ] - 2 >= 0 ) ? longest [ i - longest [ i - 1 ] - 2 ] : 0 ) ; curMax = max ( longest [ i ] , curMax ) ; } } return curMax ; } int main ( ) { string str = " ( ( ( ) ( ) " ; cout << findMaxLen ( str ) << endl ; str = " ( ) ( ( ) ) ) ) ) " ; cout << findMaxLen ( str ) << endl ; return 0 ; }