给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
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
};