Description
Longest Valid Parentheses
HardGiven 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 "()()".
Example 3:
Input: s = "" Output: 0
Constraints:
0 <= s.length <= 3 * 104s[i]is'(', or')'.
Solutions
Perfect solution first try, mostly because exhaustive test cases list was available in the comments.
Language: javascript()DONE
CPU Performance100.00%
x
Memory Performance57.72%
x
/**
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function(s) {
const stack = [];
let min = -1;
let res = 0;
for (let right = 0; right < s.length; right++) {
if (s[right] === '(') {
stack.push(right);
continue;
}
if (stack.length === 0) {
min = right;
continue;
}
stack.pop();
const left = stack.length > 0 ? stack[stack.length - 1] : min;
res = Math.max(res, right - left);
}
return res;
};