Given a string containing just the characters '('
and ')'
, find 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 "()()".
Example 3:
Input: s = "" Output: 0
Constraints:
0 <= s.length <= 3 * 104
s[i]
is'('
, or')'
.
Solution:
/**
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function(s) {
let stack = [];
// track the start position
let start = 0;
let ans = 0;
for (let i = 0; i < s.length; i++) {
// open parenthese '(' push that index of '('
if (s[i] === '(') {
stack.push(i);
} else {
// if stack empty => invalid, start from i + 1
if (stack.length === 0) {
start = i + 1;
} else {
stack.pop();
// empty stack: calculate [start...i]
// or Not empty stack calculate [index of '('...i]
// store the max length
ans = Math.max(ans, stack.length === 0 ? i - start + 1 : i - stack[stack.length - 1]);
}
}
}
return ans;
};