90.最长有效括号

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

示例1:

输入:s = "(()"
输出:2
解释:最长有效括号子串是 "()"

示例2:

输入:s = ")()())"
输出:4
解释:最长有效括号子串是 "()()"

示例3:

输入:s = ""
输出:0

提示:

  • 0 <= s.length <= 3 * 104
  • s[i] 为 '(' 或 ')'

代码:

class Solution {
    public int longestValidParentheses(String s) {
        //存储最终结果(最长有效括号长度)
        int res = 0;
        //使用栈来保存括号的索引位置
        Deque<Integer> stack = new LinkedList<>();
        //初始压入-1作为基准位置
        stack.push(-1);
        for(int i = 0;i<s.length();i++){
            //遇到左括号,压入当前索引
            if(s.charAt(i)=='(')stack.push(i);
            else{
                //遇到右括号,弹出栈顶元素(可能是匹配的左括号或分隔标记)
                stack.pop();
                //如果栈为空,说明当前右括号没有匹配的左括号
                //将当前索引作为新的基准位置压入栈
                if(stack.isEmpty())stack.push(i);
                //栈不为空,计算当前有效括号长度
                //i - stack.peek() 表示当前匹配的括号长度
                else res = Math.max(res,i-stack.peek());
            }
        }
        //返回最长有效括号长度
        return res;
    }
}
posted @ 2025-05-09 10:45  回忆、少年  阅读(15)  评论(0)    收藏  举报