32. 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> st;
        int maxLen = 0, n = s.size();

        for(int i = 0; i < n; i++){
            if(s[i] == '(')
                st.push(i);
            else if(s[i] == ')' && !st.empty() && s[st.top()] == '('){
                st.pop();
            }
            else{
                st.push(i);
            }
        }

        if(st.empty())  return n;

        int a = n, b = 0;

        while(!st.empty()){
            b = st.top(); st.pop();
            maxLen = max(maxLen,a - b - 1);
            a = b;
        }
        maxLen = max(maxLen, a);
        return maxLen;
    }
};

results matching ""

    No results matching ""