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(""));
        }
    
    }
  • 相关阅读:
    查看日志
    MySQL连接方式和启动方式
    day03--MySQL用户篇
    MySQL5.6与5.7区别
    Ansible部署主从复制
    day03--MySQL多实例及多实例主从
    MySQL体系结构
    day02-mysql编译安装误删除用户恢复
    数据库包获取方式
    day01--数据库介绍及二进制安装MySQL5.6
  • 原文地址:https://www.cnblogs.com/null00/p/5066977.html
Copyright © 2011-2022 走看看