最长有效括号

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

/**
 * @param {string} s
 * @return {number}
 */
const longestValidParentheses = (s) => {
    const len = s.length
    if (len <= 1) return 0
    const stack = [-1]
    let max = 0
    for (let i = 0; i < len; i++) {
        const v = s[i]
        if (v === '(') {
            stack.push(i)
        } else {
            stack.pop()
            if (stack.length > 0) {
                max = Math.max(max, i - stack[stack.length - 1])
            } else {
                stack.push(i)
            }
        }
    }
    return max
};

  两次循环

const longestValidParentheses = (s) => {
    let max = 0
    let left = 0
    let right = 0
    const len = s.length
    for (let i = 0; i < len; i++) { //从左往右
        if (s[i] === "(") { //遇见'(' left++
            left++
        } else {
            right++ //遇见')' right++
        }
        if (left === right) { //左右数量相同
            max = Math.max(max, 2 * left); //更新最大长度
        } else if (right > left) { //right大于left 重置left right 重新计数
            left = right = 0
        }
    }
    left = right = 0
    for (let i = len - 1; i > -1; i--) { //从右往左
        if (s[i] === "(") {
            left++
        } else {
            right++
        }
        if (left === right) {
            max = Math.max(max, right * 2);
        } else if (left > right) {
            left = right = 0
        }
    }
    return max
};

  

posted @ 2023-02-16 21:46  671_MrSix  阅读(8)  评论(0编辑  收藏  举报