32. Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

by Abhishek Kumar

JavaScript

/**
 * @param {string} s
 * @return {number}
 */
var longestValidParentheses = function(s) {
  let count = 0,
    stack = [];
  for (let i = 0; i < s.length; i++) {
    if (s[i] == '(') {
      stack.push(1);
    } else if (s[i] == ')' && stack.length > 0) {
      stack[stack.length-1]++;
    }
		if (stack[stack.length-1] == 2) {
			count += stack.pop();
		}
  }
  return count;
};

console.log(longestValidParentheses("(()"))
console.log(longestValidParentheses(")()())"))
console.log(longestValidParentheses("()(()"))
console.log(longestValidParentheses("()(())"))
console.log(longestValidParentheses("))))((((())))))))(())"))
console.log(longestValidParentheses("((()))))(())"))