思路:
本题要求找出给定字符串中最长的连续括号对
第一想法是使用双指针,但是无法通过有多余左括号的情况
第二想法是用栈记录括号成对消除,但是无法通过多个括号对不连续情况
所以最终选择用栈记录括号下标,利用下标计算最长连续个数
代码:
先初始化最大值并返回
然后开始遍历字符串
当前字符串为左括号或者消除不掉的右括号时,添加当前下标到栈
当前字符串为能消除掉的右括号时,消除并计算最大连续长度
var longestValidParentheses = function (s) {
let max = 0
let len = s.length
let stack = [-1]
for (let i = 0; i < len; i++) {
if (s[i] === '(') {
stack.push(i)
} else if (stack.length !== 0 && s[stack[stack.length - 1]] === '(') {
stack.pop()
max = Math.max(max, i - stack[stack.length - 1])
} else {
stack.push(i)
}
}
return max
};