32. Longest Valid Parentheses


July-10-2019

我会N^N的办法= =简而言之是不会做。

看答案先找出了所有违规的括号的位置,比如())默认第二个)是违规的。
找出来之后就相当于xxxxxxx违规xxxxx违规xxx违规xxx 找出最长X就行了,有EDGE CASE需要考虑:
Stack空了之后最后还要再算一次比如())这种情况

    public int longestValidParentheses(String s) {
        if (s == null || s.length() <= 1) return 0;

        ArrayDeque<Integer> stack = new ArrayDeque<>();
        for (int i = 0, strLength = s.length(); i < strLength; i ++) {
            char tempChar = s.charAt(i);
            if (tempChar == '(') {
                stack.push(i);
            } else if (tempChar == ')' && !stack.isEmpty() && s.charAt(stack.peek()) == '(') {
                stack.pop();
            } else {
                stack.push(i);
            }
        }
        if (stack.isEmpty()) {
            return s.length();
        }
        int res = 0;
        int endPos = s.length() - 1;
        while (!stack.isEmpty()) {
            int startPos = stack.pop();
            res = Math.max(res, endPos - startPos);
            endPos = startPos - 1;
        }
        res = Math.max(res, endPos + 1);
        return res; 
    }
posted @ 2019-07-11 12:10  哇呀呀..生气啦~  阅读(79)  评论(0编辑  收藏  举报