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.
Code:
<span style="font-size:14px;">class Solution {
public:
int longestValidParentheses(string s) {
int lastRight = -1;
const int length = s.size();
stack<int> stk;
int result = 0;
for (int i = 0; i < length; ++i) {
if (s[i] == '(') {
stk.push(i);
} else if (s[i] == ')') {
if (stk.empty()) {
lastRight = i;
} else {
stk.pop();
if (stk.empty()) {
result = max(result, i-lastRight);
} else
result = max(result, i-stk.top());
}
}
}
return result;
}
};</span>