← All problems

32. Longest Valid Parentheses

HardOpen on LeetCodeProblem statement

Problem Statement

32. Longest Valid Parentheses

Hard


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

 

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:

Input: s = ""
Output: 0

 

Constraints:

C++

Source file
class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> stk;
        int ans=0;
        stk.push(-1);
        for(int i=0;i<s.size();i++){
            int t= stk.top();
            if(t!=-1 && s[i]==')' && s[t]=='(')
                stk.pop(), ans=max(ans,i-stk.top());
            else
                stk.push(i);
        }
        return ans;
    }
};