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; 
        }
    
  • 相关阅读:
    常见面试题
    3*0.1 == 0.3 将会返回什么?true 还是 false?
    poj_2186 强连通分支
    强连通分量、割点、桥
    最小生成树
    poj_2349 Kruskal 最小生成树
    poj_1258 prim最小生成树
    最短路径
    poj_1125 Floyd最短路
    poj_1860 SPFA
  • 原文地址:https://www.cnblogs.com/reboot329/p/11169195.html
Copyright © 2011-2022 走看看