题目
给你一个只包含
'('
和')'
的字符串,找出最长有效(格式正确且连续)括号子串的长度。
示例
输入:s = "(()" 输出:2 解释:最长有效括号子串是 "()"
思路
可以利用leftCNum和rightCNum分别记录(数目和)数目,当左右括号数字相同的时候,一定匹配,但是在从左到右遍历过程中 如果rightCNum>leftCNum,一定不匹配,比如())
但是这样有一个问题,比如((),这个求不出答案,因为rightCNum永远不可能等于leftCNum
那么这个时候可以选择再进行一次从右往左遍历,这个时候的条件就是rightCNum<leftCNum时一定不匹配了,这样可以筛选出(()
答案
/**
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function(s) {
let ans=0;
let left=0,right=0;
let leftCNum=0,rightCNum=0;
while(right<s.length){
if(s[right]==='(') leftCNum++;
else rightCNum++;
if(leftCNum<rightCNum){
left=right+1;
leftCNum=0;
rightCNum=0;
}
if(leftCNum===rightCNum)
{
ans=Math.max(ans,rightCNum*2);
}
right=right+1;
}
left=right=s.length-1;
leftCNum=0,rightCNum=0;
while(left>=0){
if(s[left]==='(') leftCNum++;
else rightCNum++;
if(leftCNum>rightCNum){
right=left-1;
leftCNum=0;
rightCNum=0;
}
if(leftCNum===rightCNum)
{
ans=Math.max(ans,leftCNum*2);
}
left=left-1;
}
return ans;
};