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(""));
        }
    
    }
  • 相关阅读:
    闭包的应用(转载)
    智能社讲解js基础
    HTML5 Geolocation
    Redis主从配置
    Redis序列化配置
    Ribbon负载均衡原理学习记录
    2059 mysql
    Cache缓存
    rabbitmq(三)-Direct交换器
    rabbitmq(二)原理
  • 原文地址:https://www.cnblogs.com/null00/p/5066977.html
Copyright © 2011-2022 走看看