32. 最长有效括号

32. 最长有效括号

题解:

  1. 合法子串中num('(') > num(')') 左右括号的数量相等
  2. 合法序列的前缀 num('(') >= num(')') 左括号的序列要大于右括号的序列
  3. 如果出现 num('(') < num(')') 则说明这个右括号开始是不合法的,可以从该右括号为起点,重新遍历后面的子串
class Solution {
    public int longestValidParentheses(String s) {
        char[] ch = s.toCharArray();
        int n = s.length();
        if (n == 0) return 0;
        Deque<Integer> stack = new ArrayDeque<>();
        int res = 0;
        for (int i = 0, start = -1; i < n; i++) {
            if (ch[i] == '(') {
                stack.push(i);
            } else {
                if (stack.size() > 0) {
                    stack.pop();
                    if (stack.size() > 0) {
                        res = Math.max(res, i - stack.peek());
                    } else {
                        res = Math.max(res, i - start);
                    }
                } else {
                    start = i;
                }
            }
        }
        return res;
    }
}
posted @ 2022-11-06 21:52  Eiffelzero  阅读(34)  评论(0)    收藏  举报