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; 
        }
    
  • 相关阅读:
    强制ubuntu登陆用户退出
    命令行设置ubuntu 无密码自动登陆
    docker 添加普通用户权限
    CMake配置工程链接库
    配置glibc
    编译sfml
    GNOME设置快捷键
    设置jetson nano VNC
    深度学习中的基本概念——评价指标相关
    行为识别
  • 原文地址:https://www.cnblogs.com/reboot329/p/11169195.html
Copyright © 2011-2022 走看看