Leetcoed 32. 最長有效括號

給定一個只包含 '(' 和 ')' 的字符串,找出最長的包含有效括號的子串的長度。

示例 1:

輸入: "(()"
輸出: 2
解釋: 最長有效括號子串爲 "()"
示例 2:

輸入: ")()())"
輸出: 4
解釋: 最長有效括號子串爲 "()()"

一看就是stack,注意首先push(-1)

class Solution {
    public int longestValidParentheses(String s) {
        int max = 0;
        Stack<Integer> stack = new Stack<>();
        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);
                else{
                    max = Math.max(i - stack.peek(),max);
                }
                
            }
        }
        return max;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章