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.
Accept: 2ms
int longestValidParentheses(char *s) {
int stack[20000];
int p = 0;
int val[20000];
int n = 0;
for (; *s != '\0'; ++s) {
if (*s == '(') {
stack[p++] = n;
val[n++] = 0;
} else { // *s == ')':
if (p > 0) {
--p;
int i = stack[p];
val[i] = 2;
} else {
val[n++] = 0;
}
}
} // for
int longest = 0;
int cur = 0;
for (int i = 0; i < n; ++i) {
if (val[i] == 2) {
cur += 2;
} else {
if (cur > longest) {
longest = cur;
}
cur = 0;
}
}
return cur > longest ? cur : longest;
}