题解 | 最长的括号子串

最长的括号子串

https://www.nowcoder.com/practice/45fd68024a4c4e97a8d6c45fc61dc6ad

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param s string字符串
 * @return int整型
 */
function longestValidParentheses(s) {
    const n = s.length;
    const stack = [];
    let res = 0;
    let b = -1
    for (let i = 0; i < n; i++) {
        // 每次遍历到左括号的时候
        if (s[i] === "(") {
            stack.push(i);
        } else {
            // 如果出现右括号时,有左括号
            if (stack.length) {
                // 就去掉一个左括号
                stack.pop()
                // 去掉之后没有左括号了,说明从上一次分开的位置开始,整个字符串都是正确的子串
                if (!stack.length) {
                    res = Math.max(res, i - b)
                // 如果还有左括号,就从上一个左括号开始的位置到现在是正确的子串
                } else {
                    res = Math.max(res, i - stack.at(-1))
                }
            // 如果出现右括号时,没有左括号,就按照当前位置将字符串分开
            } else {
                b = i
            }
        }
    }
    return res;
}
module.exports = {
    longestValidParentheses: longestValidParentheses,
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务