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;
    }
}; 
posted @ 2014-05-29 15:57  erictanghu  阅读(102)  评论(0)    收藏  举报