Leetcode 32 Longest Valid Parentheses Solution in c++ | Hindi Coding Community

0


 Given a string containing just the characters '(' and ')', return 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 "()()".




class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length(),len =0,maxlen =0;
stack<int> st;
st.push(-1);
for(int i =0;i<n;i++)
{
if(s[i] == '(')
st.push(i);
if(s[i] == ')')
{
st.pop();
if(st.empty())
st.push(i);
len = i - st.top();
maxlen = max(maxlen,len);
}
}
return maxlen;
}
};


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !