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));
        }
    
    }
  • 相关阅读:
    浏览器渲染原理
    element 表单清空提示语(单个 )
    同步异步
    数组的浅克隆
    ... 运算符
    解构赋值
    vue 中el-input 为number 如何控制不允许输入负号
    Android SDK Manager 更新代理配置
    Android 设计中的.9.png
    Android 编程下的 Secret Code
  • 原文地址:https://www.cnblogs.com/joannacode/p/4389328.html
Copyright © 2011-2022 走看看