*
* @param s string字符串
* @return int整型
*/
function longestValidParentheses( s ) {
// write code here
let ls = 0, rs = 0;
let n = s.length;
let ans = 0;
for(let i = 0; i < n; i ++){ //正序遍历一遍
if(s[i] == '(')
ls++;
else
rs++;
if(ls == rs)
ans = Math.max(ans, ls * 2); //如果左括号与右括号数量相等则说明当前序列是合法的并更新答案
else if(rs > ls)
ls = rs = 0;
}
ls = rs = 0;
for(let i = n - 1; i >= 0; i --){ //逆序遍历一遍
if(s[i] == '(') ls ++;
else rs ++;
if(ls == rs) ans = Math.max(ans, ls * 2); //与正序一致
else if(rs < ls) ls = rs = 0;
}
return ans;
}
module.exports = {
longestValidParentheses : longestValidParentheses
};