Monday, April 27, 2015

[LeetCode] 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) {
        int maxLen = 0, last = -1;
        int len = s.length();
        
        stack<int> stack;
        for(int i=0;i<len;i++)
        {
            if(s[i] == '(')
            {
                stack.push(i);
            }
            else
            {
                if(stack.empty())
                {
                    last = i;
                    continue;
                }
                stack.pop();
                if(stack.empty())
                {
                    //last is the first ')' without matching
                    maxLen = max(maxLen, i-last);
                }
                else
                {
                    //the top of stack is the first '(' without match
                    maxLen = max(maxLen, i-stack.top());
                }
            }
        }
        return maxLen;
    }
};