16. Longest Valid Parentheses
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: 0Solution: (Using Stack)
class Solution
{
public:
int longestValidParentheses(string s)
{
stack<int> st;
st.push(-1);
int maxLen = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == ')')
{
if (st.top() != -1 && s[st.top()] == '(')
{
st.pop();
int len = i - st.top();
maxLen = max(maxLen, len);
continue;
}
}
st.push(i);
}
return maxLen;
}
};Last updated