32. 最長有效括號

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

示例 1:

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

示例 2:

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

class Solution {
    public int longestValidParentheses(String s) {
        char[] chars = s.toCharArray();
        int idx = 1,res=0;
        int[] stack = new int[chars.length+1];
        for (int i = 0;i<chars.length;i++) {
            if (chars[i]=='('){
                stack[idx++]=i;
            }else {
                if (idx==1){
                    stack[0] = i+1;
                }else {
                    idx--;
                    res = idx==1?Math.max(res,i-stack[0]+1):Math.max(res,i-stack[idx-1]);
                }
            }
        }
        return res;
    }
}

 

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