zoukankan      html  css  js  c++  java
  • 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; 
        }
    
  • 相关阅读:
    2017.8.15
    2017.8.14
    2017.8.12
    2017.8.11
    2017.8.10
    IE9下透明度设置无效
    IE7不支持Z-index问题
    IE9下支持jQuery
    IE9下支持css3的方法
    oninput、onpropertychange和onchange
  • 原文地址:https://www.cnblogs.com/reboot329/p/11169195.html
Copyright © 2011-2022 走看看