Skip to content

Latest commit

 

History

History
47 lines (41 loc) · 954 Bytes

0032. 最长有效括号.md

File metadata and controls

47 lines (41 loc) · 954 Bytes

32. 最长有效括号

给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。

https://leetcode-cn.com/problems/longest-valid-parentheses/


从左往右走一遍,从右往左走一遍。

/**
 * @param {string} s
 * @return {number}
 */
var longestValidParentheses = function(s) {
  if (!s) return 0
  var right = left = max = 0;
  for (var i = s.indexOf('('); i < s.length; i ++) {
    if (s[i] === '(') {
      left ++
    } else {
      right ++
    }
    if (left === right) {
      max = Math.max(max, right * 2)
    } else if (right > left) {
      left = right = 0
    }
  }

  left = right = 0
  for (var i = s.lastIndexOf(')'); i >= 0; i --) {
    if (s[i] === ')') {
      right ++
    } else {
      left ++
    }
    if (left === right) {
      max = Math.max(max, right * 2)
    } else if (right < left) {
      left = right = 0
    }
  }
  return max
};