Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

class Solution {
public:
     int longestValidParentheses( string s) 
    {
        stack< int> stk;
        stk.push(- 1);
         int max= 0;
        stack< char> cstk;
         for( int i= 0;i<s.length();i++)
        {
             if(s[i]== ' ( ' || cstk.empty() || cstk.top()== ' ) ')
            {
                cstk.push(s[i]);
                stk.push(i);
            }
             else
            {
                cstk.pop();
                stk.pop();
                 if(i-stk.top()>max) max=i-stk.top();
            }
        }
         return max;
    }
};  

你可能感兴趣的:(long)