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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int nSize = s.size();
if (nSize <= 1)
return 0;
stack<int> pare;
int longest = 0;
int top = nSize;
for (int i = 0; i < nSize; ++i)
{
if (s[i] == '(')
pare.push(i);
else if(!pare.empty())
{
int tmp = pare.top();
pare.pop();
top = top < tmp ? top : tmp;
if (pare.empty())
longest = longest > i - top + 1 ? longest : i - top + 1;
else
longest = longest > i - pare.top() ? longest : i - pare.top();
}
else
top = i + 1;
}
return longest;
}
};