zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

    For "(()", the longest valid parentheses substring is "()", which has length = 2.

    Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

    思路:

    在栈中保存上一个"("的位置

    package ds;
    
    import java.util.Stack;
    
    public class LongestValidParentheses {
    
        public int longestValidParentheses(String s) {
            int len;
            if (s == null || (len = s.length()) < 2) return 0;
            Stack<Integer> stack = new Stack<Integer>();
            int max = 0;
            int lastIndex = -1;
            int i = 0;
            while (i < len) {
                if (s.charAt(i) == '(') {
                    stack.push(i);
                } else {
                    if (stack.isEmpty()) {
                        lastIndex = i;
                    } else {
                        stack.pop();
                        if (stack.isEmpty()) {
                            max = Math.max(max, i - lastIndex);
                        } else {
                            max = Math.max(max, i - stack.peek());
                        }
                    }
                }
                ++i;
            }
            
            return max;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            LongestValidParentheses l = new LongestValidParentheses();
            System.out.println(l.longestValidParentheses(""));
        }
    
    }
  • 相关阅读:
    sql 计算auc
    tf.app.flags
    transformer
    python 直连 hive
    rnn 详解
    yolov3
    记学习react-native
    html5横、竖屏状态 以及禁止横屏
    图片懒加载
    npm安装的时候报-4048
  • 原文地址:https://www.cnblogs.com/null00/p/5066977.html
Copyright © 2011-2022 走看看