算法 求最长有效括号

给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。

示例 1:

输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:

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

 public int longestValidParentheses(String s) {
        int max=0;
        //创建一个栈
        Stack<Integer> stack=new Stack<>();
        //-1入栈
        stack.push(-1);
        for(int i=0;i<s.length();i++){
            if(s.charAt(i) =='('){
                //下标入栈
                stack.push(i);
            }else{
                //栈顶出栈(后进先出)
                stack.pop();
                //判断栈里是不是为空
                if(stack.empty()){
                    stack.push(i);
                }else{
                    //用i减去栈顶的元素 得到最长有效括号
                    max = Math.max(max,i-stack.peek());
                }
            }
        }
        return max;
    }
发布了28 篇原创文章 · 获赞 24 · 访问量 1081

猜你喜欢

转载自blog.csdn.net/qq_42305209/article/details/103427731
今日推荐