zoukankan      html  css  js  c++  java
  • Leetcode32. 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.

    solution:用stack,复杂度O(n)

    package leetcode2;
    
    import java.util.Stack;
    
    public class LongestValid_Parentheses {
        public static int longest_VP_DP(String s) {
            Stack<Integer> re =new Stack<Integer>();
            int start=-1;
            int maxl=0;
            int location;
            for(int i=0;i<s.length();i++){
                if (s.charAt(i)=='('){
                    re.push(i);
                }else{
                    if(re.empty()){
                        start=i;
                    }else{
                    location=re.pop();
                    if(re.empty()){
                        maxl=Math.max(maxl, i-start); //外围没有(括号了,到i已得到一个局部最大值
                    }else{
                        maxl=Math.max(maxl, re.peek()-i);  //外围还有(,没有结束哦
                    }
                    }
                }
                
            }
            return maxl;
            
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
        String string="()()(";
        System.out.println(longest_VP_DP(string));
        }
    
    }
  • 相关阅读:
    java join 方法的使用
    java wait(),notify(),notifyAll()
    java volatile关键字
    java 多线程死锁
    Java Synchronized
    Java 多线程概念
    Ubunte 11.4 下安装 SSH遇到的问题
    css sprint 生成工具 bg2css
    jquery each 用法
    error BC31019 无法写入输出文件 未指定错误
  • 原文地址:https://www.cnblogs.com/joannacode/p/4389328.html
Copyright © 2011-2022 走看看