zoukankan      html  css  js  c++  java
  • leetcode 32. Longest Valid Parentheses

    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.

    分析:

    给出一组括号,找出其中连续有效括号的最长长度。

    for循环遍历每个括号,当前位置为i,index用于记录每段有效括号的起始位置。

    (1)判断当前位置是否是左括号,如果遇到左括号,入栈。

    (2)如果不是左括号,

          1,判断栈是否为空,如果为空,将index指针后移。

          2,如果栈不为空,弹出栈顶元素。

             此时,如果栈为空,加上当前位置i的右括号可以构成一段有效的括号,最长为max(maxLen, i到index之间的距离),

             如果栈不为空,说明栈顶后一位开始到当前位置可以构成一段有效的括号,那最长为max(maxLen, i到栈顶后一位的长度)。

    public class Solution {
        public int longestValidParentheses(String s) {
            if (s == null){
               return 0; 
            }
            
            Stack<Integer> p = new Stack<Integer>();
            int maxLen = 0;
            int index = 0;
            
            for (int i = 0; i < s.length(); i++){
                if (s.charAt(i) == '('){
                   p.push(i); 
                }else{
                    if(p.isEmpty()){
                        index = i + 1;
                    }else{
                        p.pop();
                        if(p.isEmpty()){
                            maxLen = Math.max(i - index + 1, maxLen);
                        }else{
                            maxLen = Math.max(i - p.peek(), maxLen);
                        }
                    }
                }
            }
            return maxLen;
        }
    }
  • 相关阅读:
    Servlet生命周期
    DAO 开发模式的几个类
    Iterator用法
    mysql相似于oracle的to_char() to_date()方法
    Java Web页面跳转
    JSP 连接MySQL 5.1
    采用DOM进行表格的修改操作
    使用css让XML文件按照HTML的风格显示出来
    正则表达式Regular Expression
    什么是“堆”,"栈","堆栈","队列",它们的区别
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5740877.html
Copyright © 2011-2022 走看看